Spring Ioc 프로젝트 의 실현 과정 을 실례 를 통 해 해석 하 다

3559 단어 springIoc항목
0. Ioc
https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html
주로 제어 반전 을 실현 하고 결합 성 이 크게 떨어진다.
1.maven 프로젝트 구축
빈 maven 프로젝트 를 만 든 다음 pom.xml 에 spring-context 의존 도 를 추가 합 니 다.

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.7.RELEASE</version>
    </dependency>
2.pojo 자바 대상 만 들 기

package com.aca;

public class Hello {
  private String str;


  public void setStr(String str) {
    this.str = str;
  }

  public String getStr() {
    return str;
  }

  public Hello(String str){
    this.str = str;
  }


  @Override
  public String toString() {
    return "Hello{" +
        "str='" + str + '\'' +
        '}';
  }
}
3.bean xml 설정 메타 데이터 만 들 기
프로필 을 resources 아래 에 놓 습 니 다.
여 기 는 xml 를 예 로 들 면

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    https://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="Hello" class="com.aca.Hello">
    <constructor-arg type="java.lang.String" value="fffff"/>
  </bean>

</beans>
여러 개의 resource 나 디 렉 터 리 가 일치 하지 않 으 면 import 가 필요 합 니 다.

<beans>
  <import resource="services.xml"/>
  <import resource="resources/messageSource.xml"/>
  <import resource="/resources/themeSource.xml"/>

  <bean id="bean1" class="..."/>
  <bean id="bean2" class="..."/>
</beans>
안에 구조 함 수 를 호출 하여 bean 을 초기 화 할 수 있 습 니 다.
4.spring 컨 텍스트 만 들 기
여 기 는 ClassPathXmlApplication Context 방법 으로

   ApplicationContext context = new ClassPathXmlApplicationContext("hbean.xml");

// retrieve configured instance
    Hello hello = context.getBean("Hello", Hello.class);
//    hello.setStr("abc");
    System.out.println(hello);
이 bean 을 직접 사용 하여 xml 로 주입 할 수 있 습 니 다.
5.오류:java:오류:발행 버 전 5 는 지원 되 지 않 습 니 다
file-procject structure 의 jdk 버 전 을 로 컬 과 계속 선택 하 십시오.예 를 들 어 저 는 jdk 14 입 니 다.

build->자바 complier 의 두 버 전 을 로 컬 과 일치 하도록 선택 하 십시오.여 기 는 14 입 니 다.

이 두 단 계 를 다 한 후에 잘못 보고 하지 않 을 것 입 니 다.Maven 에 서 는 버 전 을 선택 할 필요 가 없습니다.
6.xml 문 제 를 보고 하면xml declaration should precede all document그것 은 xml 첫 줄 이 빈 칸 이기 때 문 입 니 다.반드시이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기