스프링(Spring) 공부
DI를 Annotation으로 변경
Leezu_
2021. 1. 6. 16:00
기존 .xml에 담긴 DI -> Annotation 으로 변경한다.
(물론, 코드가 없다면 지금까지 해왔던 것처럼 .xml 파일에 DI를 담아야한다.)
이는 @Autowired (혹은 @Resource) Annotation(어노테이션)을 사용하여
스프링 컨테이너가 자동적으로 의존 대상 객체를 찾아 해당 객체에 필요한 의존성을 주입하게 하는 것이다.
@Autowired 작동 순서
주입하려고 하는 객체의 타입이 일치 -> 객체를 자동 주입
아니라면 -> 속성명이 일치하는 bean을 컨테이너에서 찾음
이름이 없다면 -> @Qualifier 유무를 찾아 그 속성에 의존성 주입
<servlet-context.xml>
<bean id="/index" class="com.newlecture.web.controller.IndexController"/>
<bean id="/notice/list" class="com.newlecture.web.controller.notice.ListController">
<!-- 기존에 작성했던 DI를 Annotation을 위해 주석처리 -->
<!-- <property name="noticeService" ref="noticeService" /> -->
</bean>
<bean id="/notice/detail" class="com.newlecture.web.controller.notice.DetailController"/>
추가적으로 <!-- -->주석처리 아래 4줄을 .xml 파일에 적어야한다.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd
<!-- 아래서부터 새로 추가해야하는 구문 -->
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config />
<ListController.java>
private NoticeService noticeService;
// Annotation으로 Autowired 사용
@Autowired
public void setNoticeService(NoticeService noticeService) {
this.noticeService = noticeService;
}
위의 방법처럼 사용해도 무방하지만, setNoticeService 안에 무언가 할게 아니라면,
아래와 같이 사용하는 것이 간편하다.
@Autowired
private NoticeService noticeService;
//public void setNoticeService(NoticeService noticeService) {
// this.noticeService = noticeService;
//}