Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | ||||||
| 2 | 3 | 4 | 5 | 6 | 7 | 8 |
| 9 | 10 | 11 | 12 | 13 | 14 | 15 |
| 16 | 17 | 18 | 19 | 20 | 21 | 22 |
| 23 | 24 | 25 | 26 | 27 | 28 | 29 |
| 30 |
Tags
- SBS 개발
- 첫 리액트
- 자바
- 뷰 리액트
- 간단 프로젝트
- 알고리즘
- 리액트
- CompositionAPI
- react
- 경력직
- 뷰 리액트 비교
- SBS 본사
- 트리
- Vue.js
- 사내시스템
- IT시스템개발
- 오라클
- 백준
- 대문자
- e-HR
- 프로젝트 후기
- 첫 React
- 뷰
- MySQL
- 1차면접
- 백준알고리즘
- URL입력
- 면접
- 쟈스
- 웹 개발 면접 질문
Archives
- Today
- Total
리주의 프로그래밍 공부
DI를 Annotation으로 변경 본문
기존 .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;
//}
'스프링(Spring) 공부' 카테고리의 다른 글
| RestController (0) | 2021.01.12 |
|---|---|
| RequestMapping (0) | 2021.01.08 |
| 설정파일 분리하기 (0) | 2021.01.05 |
| 연결정보 분리 (0) | 2021.01.05 |
| Wildcard (0) | 2021.01.04 |