Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
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
관리 메뉴

개발합니다

[Spring] DI(Dependency Injection) - 의존 객체 주입 본문

Web/Spring

[Spring] DI(Dependency Injection) - 의존 객체 주입

돈기법 2022. 3. 24. 14:56

DI(Dependency Injection)

: 객체를 만들어 외부에서 주입하는 방식

 

1. 생성자를 이용한 의존 객체 주입

<bean id="studentDao" class="ems.member.dao.StudentDao" />

<bean id="registerService" class="ems.member.service.StudentRegisterService">
	<constructor-arg ref="studentDao" ></constructor-arg>
</bean>

 

bean으로 생성한 DAO 객체를 Service 객체에 <constructor-arg> 태그를 통해 주입 시켜줌.

 

 

2. setter를 이용한 의존 객체 주입

public void setJdbcUrl(String jdbcUrl) {
	this.jdbcUrl = jdbcUrl;
}

public void setUserId(String userId) {
	this.userId = userId;
}

public void setUserPw(String userPw) {
	this.userPw = userPw;
}
<bean id="dataBaseConnectionInfoDev" class="ems.member.DataBaseConnectionInfo">
    <property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:xe" />
    <property name="userId" value="scott" />
    <property name="userPw" value="tiger" />
</bean>

property 태그를 통해 값을 넣어줌. 
name 속성은 해당 setter 메소드 이름에서 set을 제거하고 앞글자를 소문자로 변환해서 넣어준다.

(ex. setUserId -> userId)

 

 

3. List타입 의존 객체 주입

<property name="developers">
    <list>
        <value>Cheney.</value>
        <value>Eloy.</value>
        <value>Jasper.</value>
        <value>Dillon.</value>
        <value>Kian.</value>
    </list>
</property>

list 태그를 통해 값을 넣어준다.

 

 

4. Map타입 객체 주입

<property name="administrators">
    <map>
        <entry>
            <key>
                <value>Cheney</value>
            </key>
            <value>cheney@springPjt.org</value>
        </entry>
        <entry>
            <key>
                <value>Jasper</value>
            </key>
            <value>jasper@springPjt.org</value>
        </entry>
    </map>
</property>

map 태그 안에 entry 태그에 key, value를 따로 넣어준다.

 

 

싱글톤(Singleton)

: xml을 통해 스프링 컨테이너에서 생성된 빈(Bean) 객체의 경우 동일한 타입에 대해서는 기본적으로 한 개만 생성이 되며, getBean() 메소드로 호출될 때 동일한 객체가 반환된다.


==> 메모리가 절약됨!

 


프로토타입(Prototype)

: 싱글톤 범위와 반대의 개념. 별도의 설정을 해줘야 한다.


<bean id="dependencyBean" class="scope.ex.DependencyBean" scope="prototype">
scope 속성을 prototype으로 작성해주면 해당 빈을 호출할 때마다 새로운 객체가 생성된다.