기록해! 정리해!

어노테이션과 XML 설정 병행하여 사용하기 본문

Spring

어노테이션과 XML 설정 병행하여 사용하기

zsuling 2022. 9. 20. 09:52
<?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"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-4.3.xsd">

<context:component-scan base-package="polymorphism" />

<bean id="speaker" class="polymorphism.AppleSpeaker"> 
  <property name="price"  value="100"></property>
</bean>

</beans>

package polymorphism;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;

public class TVUser {

	public static void main(String[] args) {
	  AbstractApplicationContext factory =
			  new GenericXmlApplicationContext("applicationContext.xml");
	  TV tv=(TV)factory.getBean("SamSungTV"); // SamSungTV , LgTV
	  
	  tv.powerOn();
	  tv.volumeUp();
	  tv.volumeDown();
	  tv.powerOff();
	  
	  factory.close();
	}

}

1. Component 생성

2. Speaker 주입하기

 

package polymorphism;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component("SamSungTV")
public class SamSungTV implements TV{
	
	@Autowired
	private Speaker speaker;	
	
	SamSungTV(){
		System.out.println("SamSungTV 생성자");
	}	

	@Override
	public void powerOn() {
		System.out.println("==>SamSungTV powerOn");

	}

	@Override
	public void powerOff() {
		System.out.println("==>SamSungTV powerOff");
		
	}

	@Override
	public void volumeUp() {
		speaker.volumeUp();
		
	}

	@Override
	public void volumeDown() {
		speaker.volumeDown();
	}

}

[ Setter 인젝션 사용하기 ]


package polymorphism;

public class AppleSpeaker implements Speaker {
	
	int price =0;
	
	AppleSpeaker(){
		System.out.println("AppleSpeaker 생성자 ");
	}	
	
	public void setPrice(int price) {
		this.price = price;
	}

	@Override
	public void volumeUp() {
		System.out.println("==> AppleSpeaker volumeUp ");
		System.out.println("가격:" + price);
		
	}

	@Override
	public void volumeDown() {
		System.out.println("==> AppleSpeaker volumeDown ");
		
	}

}​
Comments