English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
setter 메서드를 통해 의존성을 주입할 수도 있습니다. <bean>의 <property>자식 요소는 Setter 주입을 위해 사용됩니다. 여기서는 주입해야 할
원시 및 문자열 기반 값 부속 객체(객체 포함) 집합 값 등
우리는 원시 값과 문자열을 기반으로 설정자 메서드를 통해 주입된 값을 확인해 보겠습니다. 여기서 세 개의 파일을 생성했습니다:
Employee.java applicationContext.xml Test.java
Employee.java
이 클래스는 간단한 클래스로, id, name, city 필드와 그 설정기와 접근기, 그리고 이 정보를 표시하는 메서드를 포함하고 있습니다.
package com.w3codebox; public class Employee { private int id; private String name; private String city; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } void display(){ System.out.println(id+" "+name+" "+city); } }
applicationContext.xml
우리는 이 파일을 통해 Bean에 정보를 제공합니다. property 요소는 setter 메서드를 호출합니다.属性的value 서브 요소는 지정된 값을 할당합니다。
<?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="obj" class="com.w3codebox.Employee"> <property name="id"> <value>20</value> </property> <property name="name"> <value>Arun</value> </property> <property name="city"></property> <value>ghaziabad</value>/value> </property> </bean> </beans>
Test.java
이 클래스는 applicationContext.xml 파일에서 Bean을 가져와서 표시 메서드를 호출합니다.
package com.w3codebox; 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 e=(Employee)factory.getBean("obj"); s.display(); } }
출력:
20 Arun ghaziabad