봄의 주입

9916 단어 springinjection
이번 에는 Spring 의 주입 을 소개 합 니 다. 속성 주입, 대상 주입, 구조 방법 주입, 집합 주입 을 포함 합 니 다.소개 하기 전에 준비 작업 을 좀 하 세 요.
우선 스프링 데모 라 는 JAVA 프로젝트 를 새로 만 듭 니 다.
그리고 프로젝트 를 위해 Spring 개발 패키지 (현재 최신 버 전 은 3.2.0 버 전) 를 가 져 옵 니 다. Spring 패키지 만 가 져 오기 에는 부족 합 니 다. comons - logging 개발 패 키 지 를 다운로드 해 야 합 니 다.
Spring:http://www.springsource.org/download/community
commons-logging:http://commons.apache.org/logging/download_logging.cgi
주입 시연 을 하기 전에 테스트 클래스 가 필요 합 니 다. 간단 한 삼각형 (Triangle) 클래스 를 쓰 겠 습 니 다.
package zjut.edu.spring;

public class Triangle {

	private String type;

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}
}

그리고 main 방법 을 포함 한 테스트 클래스:
package zjut.edu.spring;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		BeanFactory factory = new ClassPathXmlApplicationContext("springconfig.xml");
		Triangle triangle = (Triangle) factory.getBean("triangle");
		System.out.println(triangle.getType());
	}

}

main 방법 에 있 는 코드 를 모 르 겠 습 니 다. 괜 찮 습 니 다. 다음 에 설명 하 겠 습 니 다.
1. 속성 주입:
보통 우 리 는 트라이앵글 류 의 인 스 턴 스 를 얻 으 려 면 이렇게 쓴다.
Triangle triangle = new Triangle();

Spring 용기 가 있 으 면 이 부분 을 대신 해 작업 을 할 것 입 니 다. 코드 를 쓰 지 않 아 도 되 지만 spring 설정 파일 이 필요 합 니 다. 여기 서 springconfig. xml (classpath 에 넣 습 니 다) 라 고 가정 합 니 다.그 내용 은:
<?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
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
		
	<bean id="triangle" class="zjut.edu.spring.Triangle">
		<property name="type" value="saojiaoxing"/>
	</bean>
</beans>

이 프로필 에서 먼저 루트 노드 beans 이 고 루트 노드 아래 는 하위 노드 bean 입 니 다.
만약 우리 가 속성 주입 을 실현 하려 면, 자신의 bean 을 써 야 합 니 다:
	<bean id="triangle" class="zjut.edu.spring.Triangle">
		<property name="type" value="sanjiaoxing"/>
	</bean>

bean 태그 의 id 속성 은 인 스 턴 스 이름 을 대표 합 니 다. class 속성 대표 클래스 의 전체 경로 (full qualified name) 입 니 다. 그 다음 에 bean 태그 내부 에 property 하위 태그 가 있 습 니 다. 속성 할당 을 담당 합 니 다. name 은 Triangle 류 의 속성 명 (type) 에 대응 하고 value 속성 은 이름 을 속성 값 으로 생각 합 니 다.
프로필 이 배 치 된 후에 이 bean 을 얻 으 려 면 먼저 프로필 을 읽 어야 합 니 다.
		BeanFactory factory = new ClassPathXmlApplicationContext("springconfig.xml");

ClassPathXmlApplication Context 는 클래스 경로 의 xml 파일 을 읽 는 것 을 담당 하기 때문에 spring 프로필 은 src 디 렉 터 리 에 두 어야 합 니 다 (물론 String API 에 다른 클래스 가 있 습 니 다. 설정 파일 을 src 디 렉 터 리 에 두 지 않 아 도 됩 니 다). 이 클래스 는 bean 공장 으로 되 돌아 갑 니 다. 이 공장 은 설정 파일 을 읽 고 bean 대상 으로 돌아 갑 니 다.
		Triangle triangle = (Triangle) factory.getBean("triangle");

공장 을 호출 하 는 방법 getBean 입 니 다. 들 어 오 는 값 은 bean 태그 의 id 속성 값 입 니 다. Object 대상 을 되 돌려 주기 때문에 강제 변환 이 필요 합 니 다.
		System.out.println(triangle.getType());

실행 해 보 세 요.
    19, 2012 10:46:34    org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1263db: startup date [Mon Nov 19 22:46:34 CST 2012]; root of context hierarchy
    19, 2012 10:46:34    org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [springconfig.xml]
    19, 2012 10:46:35    org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@36eb76: defining beans [triangle]; root of factory hierarchy
sanjiaoxing

2. 대상 주입, 위의 예 에서 Triangle 의 필드 는 String 유형 입 니 다. 물론 원시 스타일 (Primitive Type) 일 수도 있 습 니 다. 만약 에 저희 가 Triangle 류 를 조금 만 개조 하면:
package zjut.edu.spring;

public class Triangle {

	private Point point;

	public Point getPoint() {
		return point;
	}

	public void setPoint(Point point) {
		this.point = point;
	}

	public void draw() {
		System.out.println(point);
	}
}

type 속성 을 취소 하고 Point 형식의 필드 로 바 꿉 니 다 (삼각형 이 약간 있 기 때 문 입 니 다).
package zjut.edu.spring;

public class Point {

	private int x;
	private int y;
	public int getX() {
		return x;
	}
	public void setX(int x) {
		this.x = x;
	}
	public int getY() {
		return y;
	}
	public void setY(int y) {
		this.y = y;
	}
	
	@Override
	public String toString() {
		return "Point [x=" + x + ", y=" + y + "]";
	}

}

우리 의 Point 클래스 도 간단 합 니 다. 가로 좌표 가 있 고 toString () 방법 을 덮어 씁 니 다. (데 이 터 를 테스트 하기 위해 서)
현재 우 리 는 여전히 Point 를 Triangle 클래스 에 주입 하고 싶 습 니 다. 설정 파일 에 서 는 이렇게 bean 을 써 야 합 니 다.
	<bean id="triangle" class="zjut.edu.spring.Triangle">
		<property name="point">
		    <bean class="zjut.edu.spring.Point">
		        <property name="x" value="1" />
		        <property name="y" value="2" />
		    </bean>
		</property>
	</bean>

triangle 태그 에 point 속성 태그 가 있 습 니 다. 이 속성 은 Object 형식 이기 때문에 property 태그 에 내부 bean 을 삽입 하 였 습 니 다. 이 bean 의 기능 은 point 대상 을 예화 하고 이 대상 의 가로 좌표 에 값 을 부여 하 는 것 입 니 다 (1, 2).
물론 우 리 는 내부 bean 과 triangle 의 bean 을 평행 으로 할 수 있다.
	<bean id="triangle" class="zjut.edu.spring.Triangle">
		<property name="point" ref="point0"></property>
	</bean>
	
   <bean id="point0" class="zjut.edu.spring.Point">
		<property name="x" value="1" />
		<property name="y" value="2" />
   </bean>

bean 을 설정 한 후, 우 리 는 주 클래스 에서 테스트 합 니 다:
	public static void main(String[] args) {
		BeanFactory factory = new ClassPathXmlApplicationContext("springconfig.xml");
		Triangle triangle = (Triangle) factory.getBean("triangle");
		triangle.draw();
	}
    19, 2012 10:59:06    org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1263db: startup date [Mon Nov 19 22:59:06 CST 2012]; root of context hierarchy
    19, 2012 10:59:07    org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [springconfig.xml]
    19, 2012 10:59:07    org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@161116f: defining beans [triangle,point0]; root of factory hierarchy
Point [x=1, y=2]

3. 구조 방법 주입.
servlet 용기 관리 servlet 처럼 bean 의 수명 주기 도 Spring 용기 에서 관리 합 니 다. 속성 값 을 초기 화 하 는 방법 으로 할당 하려 면 이렇게 bean 을 써 야 합 니 다.
우 리 는 삼각형 을 고 쳐 썼 다.
package zjut.edu.spring;

public class Triangle {

	private String type;

	public Triangle(String type) {
		this.type = type;
	}

	public void draw() {
		System.out.println(type);
	}
}

간단하게 하기 위해 서 이 구조 방법의 매개 변 수 는 String 형식 입 니 다. (Object 유형 은 직접 시도 해 볼 수 있 습 니 다)
	<bean id="triangle" class="zjut.edu.spring.Triangle">
		<constructor-arg index="0" value="I'm triangle"></constructor-arg>	
	</bean>

constructor - arg 라벨 은 구조 방법 이 주입 하 는 핵심 라벨 입 니 다. index 속성 은 매개 변수의 위 치 를 표시 하고 value 는 매개 변수 값 을 표시 합 니 다 (type 속성 도 있 습 니 다. 이 매개 변수의 유형 을 설명 합 니 다)
마지막 주입: 집합 주입, 트라이앵글 류 를 다시 고 칩 시다.
package zjut.edu.spring;

import java.util.List;

public class Triangle {

	private List<Point> points;
	
	public List<Point> getPoints() {
		return points;
	}

	public void setPoints(List<Point> points) {
		this.points = points;
	}

	public void draw() {
		for(Point point : points) {
			System.out.println(point);
		}
	}
}

이 필드 는 집합 형식 입 니 다. 프로필 에 있 는 bean 탭 을 어떻게 쓰 는 지 보 겠 습 니 다.
	<bean id="triangle" class="zjut.edu.spring.Triangle">
		<property name="points">
		    <list>
		        <ref bean="point0"/>
		        <ref bean="point1"/>
		        <ref bean="point2"/>
		    </list>
		</property>	
	</bean>
	
	<bean id="point0" class="zjut.edu.spring.Point">
	    <property name="x" value="0" />
	    <property name="y" value="20"/>
	</bean>
	
	<bean id="point1" class="zjut.edu.spring.Point">
	    <property name="x" value="0" />
	    <property name="y" value="-20"/>
	</bean>
	
	<bean id="point2" class="zjut.edu.spring.Point">
	    <property name="x" value="10" />
	    <property name="y" value="10"/>
	</bean>

우리 의 출력 을 보 세 요:
Point [x=0, y=20]
Point [x=0, y=-20]
Point [x=10, y=10]

오 버... 억지로

좋은 웹페이지 즐겨찾기