BackEnd/Spring

[Setter Injection] p Namespace

코딩마루 2023. 4. 28. 07:07

1. p Namespace란?

p Namespace를 사용하면 Setter Injection을 좀 더 효율적으로 DI를 처리할 수 있다. p Namespace는 아래와 같이 Namespace만 선언하면 사용할 수 있다.

xmlns:p="http://www.springframework.org/schema/p"

위와 같이 p Namespace를 선언하면 아래와 같이 참조형 변수에 참조할 객체를 할당할 수 있다.

p:(Variable Name)-ref="참조할 객체의 이름 혹은 아이디"

기본 데이터 타입은 아래와 같이 직접 값을 설정할 수 있다.

p:(Variable Name)="설정할 값"

2. 사용 예시

Setter Injection을 p Namespace를 활용하지 않으면 아래와 같이 <property> 태그를 사용해야 한다.

<?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="MyExam.Car">
        <property name="engine" ref="engineB"></property>
        <property name="seats" value="2"></property>
    </bean>

    <bean id="engineA" class="MyExam.EngineA"></bean>
    <bean id="engineB" class="MyExam.EngineB"></bean>
</beans>

만약 p Namespace를 사용하면 아래와 같이 작성 가능하다.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="car" class="MyExam.Car" p:engine-ref="engineA" p:seats="2"></bean>

    <bean id="engineA" class="MyExam.EngineA"></bean>
    <bean id="engineB" class="MyExam.EngineB"></bean>
</beans>