스프링 프레임워크(25) Bean, Property

넙데데맨·2022년 6월 17일
0

Bean 의존 관계 설정

Setter Injection

<property>태그를 이용해 주입
Hello.java

package myspring.di.xml; // class="myspring.di.xml.Hello"
public class Hello { //id="hello" 
	private String name;
	private Printer printer;
	

	public void setName(String name) { // <property name="name" value="Spring"/>
		this.name = name;
	}

	public void setPrinter(Printer printer) {//<property name="printer" ref="printer"/>
		this.printer = printer;
	}

beans.xml

	<bean id="hello" class="myspring.di.xml.Hello">	
    	<property name="name" value="Spring"/>
    	<property name="printer" ref="printer"></property>
    </bean>
    <bean id="printer" class="myspring.di.xml.StringPrinter"/>

Constuctor Injection

<Constructor>태그를 이용해 주입
Hello.java

package myspring.di.xml; // class="myspring.di.xml.Hello"
public class Hello { //id="hello" 
	private String name;
	private Printer printer;
	
	public Hello(String name, Printer printer){ // 생성자 인자를 index로 지정
    this.name = name;
    this.printer = printer;
    }
	

beans.xml

	<bean id="hello" class="myspring.di.xml.Hello">	
    	<constructor-arg index="0" value="Spring"/>
    	<constructor-arg index="1" ref="printer"/>
    </bean>
    
    <bean id="printer" class="myspring.di.xml.StringPrinter"/>

Property 값 설정

단일 값 주입

<property>의 value 속성 사용

컬렉션 타입 값 주입

list, set, map 등의 컬렉션 타입의 값 주입

List

<list> 태그와 <value> 태그 사용
Hello.java

	public class Hello {
	List<String> names;

	public void setNames(List<String> names) {
		this.names = names;
	}
	

beans.xml

		<bean id="hello" class="myspring.di.xml.Hello">	
    	<property name="names">
    		<list>
    			<value>Spring</value>
    			<value>IoC</value>
    			<value>DI</value>
    		</list>
    	</property>
    </bean>

Map

<map> 태그와 <entry> 태그 사용
Hello.java

	public class Hello {
	Map<String,Integer> ages;

	public void setAges(Map<String,Integer> ages) {
		this.ages = ages;
	}
	

beans.xml

		<bean id="hello" class="myspring.di.xml.Hello">	
    	<property name="ages">
			<map>
              <entry key="Kim" value="30" />
              <entry key="Lee" value="40" />
            </map>
    	</property>
    </bean>

Properties 파일 이용 설정

기존 값을 고정해야하는 코드들은 properties 파일을 사용해서 불러오는 것이 편하다.
<context:property-placeholder> 사용을 위해 beans.xml파일의 namespace에서 context 체크

value.properties

myname=Spring
myprinter=printer
value1=AOP
value2=Spring
value3=DI

beans.xml

	<context:property-placeholder location="classpath:config/value.properties"/>

	<bean id="hello" class="myspring.di.xml.Hello">	
    	<constructor-arg index="0" value="${myname}"/>
    	<constructor-arg index="1" ref="${myprinter}"/>
    	<property name="names">
    		<list>
    			<value>${value1}</value>
    			<value>${value2}</value>
    			<value>${value3}</value>
    		</list>
    	</property>
    </bean>
profile
차근차근

0개의 댓글