내용

글번호 693
작성자 heojk
작성일 2017-06-20 17:57:07
제목 아노테이션을 이용한 빈 설정과 의존성 주입
내용 IHelloService.java
package kr.or.kosa.msg;

public interface IHelloService {
	String sayHello(String name);
}
HelloService.java
package kr.or.kosa.hello;

import org.springframework.stereotype.Service;

@Service
public class HelloService implements IHelloService {

	@Override
	public String sayHello(String name) {
		return "Hello~~~" + name;
	}

}
HelloController.java
package kr.or.kosa.hello;

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

@Controller
public class HelloController {
	
	@Autowired
	IHelloService helloService;
	
	public void hello(String name) {
		System.out.println(helloService.sayHello(name));
	}
}
applicationContext.xml
<?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-3.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

	<bean id="empRepository" class="kr.or.kosa.emp.dao.EmpRepositoryImpl"/>
	<bean id="empService" class="kr.or.kosa.emp.service.EmpServiceImpl">
		<constructor-arg ref="empRepository"/>
	</bean>

	<context:component-scan base-package="kr.or.kosa.hello"/>

</beans>
HelloMain.java
package kr.or.kosa.hello;

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

public class HelloMain {

	public static void main(String[] args) {
		AbstractApplicationContext context =
				new ClassPathXmlApplicationContext("applicationContext.xml");
		HelloController controller = context.getBean("helloController", HelloController.class);
		controller.hello("홍길동");
		context.close();
	}

}
NiceService.java
package kr.or.kosa.hello;

import org.springframework.stereotype.Service;

@Service
public class NiceService implements IHelloService {

	@Override
	public String sayHello(String name) {
		return "Nice~~" + name;
	}

}
HelloController.java
package kr.or.kosa.hello;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;

@Controller
public class HelloController {
	
	@Autowired
	@Qualifier("niceService")
	IHelloService helloService;
	
	public void hello(String name) {
		System.out.println(helloService.sayHello(name));
	}
}