Notice
Recent Posts
Recent Comments
Link
«   2024/12   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

Kim Hyeong

스프링 DI(Dependency Injection) 2 본문

Spring

스프링 DI(Dependency Injection) 2

김형완 2018. 8. 20. 15:32

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' 카테고리의 다른 글

Component  (0) 2018.08.21
유효성 검사  (0) 2018.08.21
스프링 DI(Dependency Injection) 1  (0) 2018.08.20
스프링 MVC 흐름과 주요 구성 컴포넌트  (0) 2018.08.16
Spring Framework의 기본적인 개념  (0) 2018.08.10
Comments