@Autowired
package com.test.Ex01;
public interface Car {
String getBrand();
}
package com.test.Ex01;
public class HDCar implements Car {
public String getBrand(){
return "현대자동차!!!";
}
}
package com.test.Ex01;
public class DWCar implements Car {
public String getBrand(){
return "대우자동차!!";
}
}
package com.test.Ex01;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class User {
@Autowired // 별도의 getter, setter 설정이 필요없다. XML파일에서 property 설정이 필요없다. 자동으로 설정됨.
@Qualifier("dwcar") // 동일한 타입의 Bean 객체가 여러 개 있는 경우에 특정 Bean 객체를 선택적으로 주입할 때 사용
Car car;
// public Car getCar(){
// return car;
// }
//
// public void setCar(Car car){
// this.car = car;
// }
public String getCarBrand(){
return "선택한 차는: " + car.getBrand();
}
}
package com.test.Ex01;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
public class UserTest {
public static void main(String[] args){
AbstractApplicationContext ctx = new GenericXmlApplicationContext("classpath:car.xml");
User user = (User)ctx.getBean("user",User.class);
System.out.println(user.getCarBrand());
}
}
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:annotation-config /> // @Autowired 사용시 필히 설정해야 함.
<bean id="hdcar" class="com.test.Ex01.HDCar" />
<bean id="dwcar" class="com.test.Ex01.DWCar" />
<bean id="user" class="com.test.Ex01.User" >
<!-- <property name="car" ref="hdcar"></property> -->
<!-- <property name="car" ref="dwcar"></property> -->
</bean>
</beans>
네임스페이스에서 context 체크