본문 바로가기

spring/기초

constructor injection 생성자 주입

<?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-3.2.xsd">

<!-- constructor injection -->

<bean id="dataDaoImpl" class="model.DataDaoImpl"/> <!-- 인자가 없는 생성자 객체생성 -->

<bean id="selectServiceImpl" class="controller.SelectServiceImpl"> <!-- 인자가 하나있는 생성자 객체생성 -->

<!-- 인자(argument) 넘겨줄때 -->

<constructor-arg>

<ref bean="dataDaoImpl"/> <!-- 직접 class=""로 명시해줘도 된다. -->

</constructor-arg>

</bean>

</beans>


스프링은 자바소스에서 객체를 생성하지 않고 스프링 컨테이너에서 객체를 만든 후 자바소스에서 스프링이 만들어 놓은 객체를 가져다 쓰기만 하면된다.


위의 예제는 


객체를 만들때 생성자가 기본생성자가 아닌 인자가 있는 생성자의 객체를 생성할때 어떻게 하는가를 보여주는 예제이다.