728x90


이번에는 애너테이션을 이용해서 IoC를 구현하도록 하는 법을 배워보도록하자.

그러면 기존과 과거의 비교를 통해서 얼마나 더 쉽게 사용할 수 있는지 보도록 하자.


https://github.com/justkukaro/SpringSampleRepository/tree/master/Ch04


예제 코드는 위 github에서 확인할 수 있다.


먼저 각자의 component들이 될 객체를 보도록하자.



Game 인터페이스를 상속받아서 Soccer 클래스와 Track 클래스를 만들었다.

이제 의존성을 주입할 applicationContext.xml을 보도록 하자.



위의 코드는 bean으로 DI하는 방법이다.



이제 main클래스로 예제코드를 돌려보면 제대로 돌아가는걸 알 수 있다.


지금 까지 방법도 상당히 편한데 인간의 욕심은 끝이 없다.

그럼 xml도 안쓰고 더 쉽게 bean으로 정할수 없느냐 라고 묻는다면 가능하다고 대답하고싶다.

이 방법이 바로 annotation을 사용한 방법이다.

이제 위의 코드들 더 쉽게 사용하기 위해서 알아야하는 것은 context namespace와 component scan이다.


context namespace


<?xml version="1.0" encoding="UTF-8"?>
<!--applicationContext.xml-->
<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.xsd">
<context:component-scan base-package="net.theceres.dto"></context:component-scan>
</beans>

이제 bean을 모두 삭제해버리자. 그리고 context네임 스페이스를 추가해준뒤에 component scan을 설정해준다.


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

위 처럼 한줄을 beans에 추가한다.


http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"

이렇게 두 줄을 xsi:schemaLocation에 위의 두개를 추가해준다.

이제 context를 사용할 준비는 끝났다.


component-scan


<context:component-scan base-package="net.theceres.dto"></context:component-scan>

컴포넌트 스캔이라는 것은 component 애너테이션을 걸어놓은 모든 애들을 찾아가서 자동으로 bean을 생성하게 된다.

이제 끝났다????


정말??


이제 코드만 살짝 수정해주자.


@Component("soccer")
public class Soccer implements Game {
private boolean ball;
private int peopleCount;

이제 각각의 bean이 될 파일들 을 쫓아가서 애너테이션과 id를 정해준다.


public static void main(String[] args) {
AbstractApplicationContext factory = new GenericXmlApplicationContext("applicationContext.xml");
Game g1 = (Game) factory.getBean("soccer");
g1.info();

Game g2 = (Game) factory.getBean("track");
g2.info();
}

이제 다시 메인을 작용하면 제대로 적용되는 것을 알 수 있다.


https://github.com/justkukaro/SpringSampleRepository/tree/master/Ch04

제대로 예제코드를 확인하고 싶다면 이 레포지터리의 new를 확인하시라.


'Programming > Java-Spring' 카테고리의 다른 글

[Spring-05]애너테이션 - 의존성 주입  (0) 2018.10.27
[Spring-03]DI와 설정자(Setter) 인젝션  (0) 2017.11.13
[Spring-02]DI와 생성자 인젝션  (0) 2017.11.08
[Spring-01]IoC  (0) 2017.10.09

+ Recent posts