Setter로 DI 주입
package com.spring4.practice01;
public interface Car {
public String brand();
}
package com.spring4.practice01;
public class CarHDImpl implements Car {
public String brand(){
return "자동차는 현대자동차 소나타입니다.";
}
}
package com.spring4.practice01;
import org.springframework.beans.factory.annotation.Autowired;
public class Service {
private Car car;
public Service(){}
public void setCar(Car car){
this.car = car;
}
public void print(){
System.out.println("brand: "+car.brand());
}
}
생성자 방식과 다른 건 setCar에서 setXxx 이후 이름과 property name이름이 같은면 된다.
즉 setCar에서 Car의 첫 대문자만 소문자로 바꾸고 name을 설정하면 된다.
<?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.xsd">
<bean id="car" class="com.spring4.practice01.CarHDImpl" />
<bean id="service" class="com.spring4.practice01.Service">
<property name="car" ref="car"/>
</bean>
</beans>
package com.spring4.practice01;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
public class MainCar {
public static void main(String[] args) {
ApplicationContext ctx = new GenericXmlApplicationContext("classpath:carBean.xml");
Service service = ctx.getBean("service",Service.class);
service.print();
}
}
'기존카테고리 > Spring_문법' 카테고리의 다른 글
servletSession과 springSession (0) | 2017.07.27 |
---|---|
스프링 DI - 자바코드 설정 (0) | 2017.07.23 |
스프링 DI(Dependency Injection) 1 (0) | 2017.07.23 |
Parameter값 받기 - 실전(Command객체) (0) | 2017.07.13 |
Parameter값 받기 - 기초(@RequestParam) (0) | 2017.07.13 |