이 기사에서는 예제를 통해 Spring Bean의 기본 관리에 대해 설명합니다. 참고할 수 있도록 모든 사람과 공유하세요. 세부정보는 다음과 같습니다.
1. setter 메소드를 사용하여 종속성 주입을 완료합니다.
다음은 Bean 및 beans-config.xml 파일입니다.
public class HelloBean { private String helloWord; //...getter 및 setter 메소드 생략}
<?xml version="1.0" 인코딩="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN" "http://www.springframework.org/dtd/spring-beans. dtd"> <beans> <bean id="helloBean" > <property name="helloWord"> <value>Hello!Justin!</value> </property> </빈> </빈즈>
public class SpringDemo { public static void main(String[] args) { Resource rs = new FileSystemResource("beans-config.xml"); BeanFactory 공장 = new XmlBeanFactory(rs) hello = (HelloBean) Factory.getBean(" helloBean"); System.out.println(hello.getHelloWord()); } }
2. 생성자 메서드를 사용하여 주입을 완료합니다.
public class HelloBean { private String helloWord; // 매개변수 없는 생성 방법을 사용하는 것이 좋습니다. public HelloBean() { } public HelloBean(String name, String helloWord) { this.name = helloWord; ; } //...getter 및 setter 메서드 생략}
<?xml version="1.0" 인코딩="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN" "http://www.springframework.org/dtd/spring-beans. dtd"> <beans> <bean id="helloBean" > <constructor-arg index="0"> <value>저스틴</value> </constructor-arg> <constructor-arg index="1"> <value>안녕하세요</value> </constructor-arg> </bean> </beans>
public class SpringDemo { public static void main(String[] args) { ApplicationContext context = new FileSystemXmlApplicationContext("beans-config.xml") HelloBean hello = (HelloBean) context.getBean("helloBean"); ("이름: "); System.out.println(hello.getName()); System.out.print("단어: "); System.out.println(hello.getHelloWord()) } }
3. 속성 참조
public class HelloBean { private String helloWord; private Date date //...getter 및 setter 메소드 생략}
<beans> <bean id="dateBean"/> <bean id="helloBean"> <property name="helloWord"> <value>안녕하세요!</value> </property> <property name="date"> < ref bean="dateBean"/> </property> </bean> </beans>
public class SpringDemo { public static void main(String[] args) { ApplicationContext context = new FileSystemXmlApplicationContext("beans-config.xml") HelloBean hello = (HelloBean) context.getBean("helloBean"); (hello.getHelloWord()); System.out.print(" 이것은 "); System.out.print(hello.getDate()); System.out.println(".");
4. "byType" 자동 바인딩
Type별 Bean 속성 자동 바인딩을 완료하려면 "Three"의 구성 파일을 다음과 같이 변경한다.
<beans> <bean id="dateBean"/> <bean id="helloBean" autowire="byType"> <property name="helloWord"> <value>안녕하세요!</value> </property> </bean> </beans>
5. "byName" 자동 바인딩
이름별로 Bean 속성의 자동 바인딩을 완료하려면 "Three"의 구성 파일을 다음과 같이 변경하십시오.
<beans> <bean id="dateBean"/> <bean id="helloBean" autowire="byName"> <property name="helloWord"> <value>안녕하세요!</value> </property> </bean> </beans>
6. "생성자" 자동 바인딩
생성 방법에 따라 Bean 속성 자동 바인딩을 완료하려면 "Three"의 구성 파일을 다음과 같이 변경한다. 종속 관계를 설정할 때 Spring 컨테이너는 컨테이너의 Bean 인스턴스 유형과 관련 생성자의 매개변수 유형을 비교하여 유형이 일치하는지 확인합니다. 그렇다면 생성자를 사용하여 Bean을 생성합니다. . 바인딩할 수 없는 경우 org.springframework.beans.factory.UnsatisfiedDependencyException 예외가 발생합니다.
<beans> <bean id="dateBean"/> <bean id="helloBean" autowire="constructor"> <property name="helloWord"> <value>안녕하세요!</value> </property> </bean> </beans>
6. "자동 감지" 자동 바인딩
Bean 속성의 자동 바인딩을 완료하려면 "Three"의 구성 파일을 다음과 같이 변경하세요. 이 자동 바인딩은 Spring이 생성자를 사용하여 종속성 설정을 처리하려고 시도함을 의미합니다. 작동하지 않으면 byType을 사용해 보세요. 종속성을 설정하는 클래스입니다.
<beans> <bean id="dateBean"/> <bean id="helloBean" autowire="autoDetect"> <property name="helloWord"> <value>안녕하세요!</value> </property> </bean> </beans>
7. 의존성 확인 방법
자동 바인딩에서는 각 속성이 정의 파일에서 설정되었는지 명확하게 확인할 수 있는 방법이 없으므로 특정 종속성이 실제로 설정되었는지 확인하기 위해 <bean> 태그를 사용할 때 종속성 검사를 설정할 수 있습니다. 종속성 검사"에는 단순, 개체, 모두 및 없음의 네 가지 종속성 검사 방법이 있습니다.
simple: 단순 유형(예: 기본 데이터 유형 또는 문자열 객체)의 속성이 종속성을 완료하는지 여부만 확인합니다.
개체: 개체 유형의 속성이 종속성을 완료하는지 확인합니다.
all: 모든 속성이 종속성을 완료하는지 확인합니다.
없음: 설정이 기본값이며 종속성을 확인하지 않음을 나타냅니다.
<beans> <bean id="dateBean"/> <bean id="helloBean" autowire="autoDetect" dependencyeny-check="all"> <property name="helloWord"> <value>안녕하세요!</value> < /속성> </bean> </beans>
8. 컬렉션 객체 주입
배열, 목록, 세트 및 맵과 같은 컬렉션 개체의 경우 일부 개체는 주입 전에 컬렉션에 채워야 합니다. 그런 다음 컬렉션 개체가 필요한 Bean에 주입되면 Spring의 IoC 컨테이너에 의해 자동으로 유지 관리되거나 생성될 수도 있습니다. 컬렉션 개체 및 완전한 종속성 주입.
공개 클래스 SomeBean { 비공개 Some[] someObjArray; 비공개 지도 someMap; 공개 String[] getSomeStrArray } 공개 void setSomeStrArray(String[] someStrArray) someStrArray; } 공개 Some[] getSomeObjArray() { someObjArray 반환 } 공개 무효; setSomeObjArray(Some[] someObjArray) { this.someObjArray = someObjArray; } public List getSomeList() { return someList; } public void setSomeList(List someList) { this.someList = someList } public Map getSomeMap() { return someList; 공개 무효 setSomeMap(Map someMap) { this.someMap = someMap } }공개 클래스; Some { private String name; public String getName() { return name; } public void setName(String name) { this.name = name } public String toString() { return name;
<?xml version="1.0" 인코딩="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN" "http://www.springframework.org/dtd/spring-beans. dtd"> <beans> <bean id="some1"> <property name="name"> <value>저스틴</value> </property> </bean> <bean id="some2"> <property name="name"> <value>momor</value> </property> </bean> <bean id="someBean"> <property name="someStrArray"> <list> < value>안녕하세요</value> <value>환영합니다</value> </list> </property> <property name="someObjArray"> <list> <ref bean="some1"/> <ref bean="some2"/> </list> </property> <property name="someList"> <list> <value>ListTest</value> <ref bean="some1"/> <ref bean="some2" /> </list> </property> <property name="someMap"> <map> <entry key="MapTest"> <value>안녕하세요!저스틴!</value> </entry> <entry key="someKey1 "> <ref bean="some1"/> </entry> </map> </property> </bean> </beans>
public class SpringDemo { public static void main(String[] args) { ApplicationContext context = new FileSystemXmlApplicationContext( "beans-config.xml"); SomeBean someBean = (SomeBean) context.getBean("someBean"); // 배열 유형 가져오기 상태 기반 종속성 주입 객체 String[] strs = (String[]) someBean.getSomeStrArray() Some[] somes = (Some[]) someBean.getSomeObjArray(); for(int i = 0; i < strs.length; i++) { System.out.println(strs[i] + "," + somes[i].getName() ); } // 목록 유형 종속성 주입 객체 가져오기 System.out.println(); List someList = (List) someBean.getSomeList() for(int i = 0; i < someList.size(); i++) { System.out.println(someList.get(i)) } // Map 유형 종속성 주입 객체 가져오기 System.out.println(); (); System.out.println(someMap.get("MapTest")); System.out.println(someMap.get("someKey1")); }
이 글이 Java 프로그래밍에 종사하는 모든 분들께 도움이 되기를 바랍니다.