본문 바로가기

기존카테고리/Spring_문법

스프링 DI(Dependency Injection) 2

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();


}

}