English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

의존성 생성자 주입 예제

의존성을 생성자 주입으로 주입할 수 있습니다. <bean><constructor-arg>생성자 주입을 위한 서브 요소. 여기서 주입할

원시와 문자열 기반의 값 부속 객체(객체 포함) 집합 값 등

원시 값과 문자열 기반의 값

원시 값과 문자열 기반의 간단한 예제 가치를 보여드리겠습니다. 여기서 세 개의 파일을 생성했습니다:

Employee.java applicationContext.xml Test.java

Employee.java

이 클래스는 두 필드 id와 name을 포함한 간단한 클래스입니다. 이 클래스에는 네 개의 생성자와 하나의 메서드가 있습니다.

package com.w;3codebox;
public class Employee {
private int id;
private String name;
public Employee() { System.out.println("def cons");}
public Employee(int id) { this.id = id;}
public Employee(String name) { this.name = name;}
public Employee(int id, String name) {
    this.id = id;
    this.name = name;
}
void show(){
    System.out.println(id+"+name);
}
}


applicationContext.xml

우리는 이 파일을 통해 정보를 Bean에 제공합니다. constructor-arg 요소는 생성자를 호출합니다. 이 경우 int 타입의 파라미터화된 생성자가 호출됩니다. Constructor-arg 요소의 value 속성은 지정된 값을 할당합니다. type 속성은 int 파라미터 생성자를 호출합니다。

<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance
    xmlns:p="http://www.springframework.org/schema/p
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="e" class="com.w3codebox.Employee">
<constructor-arg value="10" type="int"></constructor-arg>
</bean>
</beans>

Test.java

이 클래스는 applicationContext.xml 파일에서 Bean을 가져와 show 메서드를 호출합니다。

package com.w;3codebox;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;
public class Test {
    public static void main(String[] args) {
        
        Resource r=new ClassPathResource("applicationContext.xml");
        BeanFactory factory=new XmlBeanFactory(r);
        
        Employee s=(Employee)factory.getBean("e");
        s.show();
        
    }
}

출력: 10공백


문자 기반의 값 주입

생성자 arg 요소에 type 속성을 지정하지 않으면 기본적으로 문자 타입 생성자가 호출됩니다

....
<bean id="e" class="com.w3codebox.Employee">
<constructor-arg value="10></constructor-arg>
</bean>
....

bean 요소를 위와 같이 변경하면 문자 매개변수 생성자가 호출되고 출력은 0이 됩니다 10。

출력: 0 10


문자열 문자를 다음과 같이 전달할 수도 있습니다:

....
<bean id="e" class="com.w3codebox.Employee">
<constructor-arg value="Sonoo"></constructor-arg>
</bean>
....

출력: 0 Sonoo


정수 문자와 문자열을 다음과 같이 전달할 수 있습니다:

....
<bean id="e" class="com.w3codebox.Employee">
<constructor-arg value="10" type="int""></constructor-arg>
<constructor-arg value="Sonoo"></constructor-arg>
</bean>
....

출력: 10 Sonoo