@Component
@Autowired는 XML 파일에서 객체를 불러올 때, 특정 값을 지정해둔 채로 가져오기 위해서 사용한다.
이에 비해 @Component는 XML 파일에서 객체를 불러온다는 언급이 없더라도, @Component가 있는 객체를 자동으로 가져오기 위해 사용한다.
@Component 종류
이름은 다르지만 @Component와 같은 기능을 한다. 코드의 가독성을 높이기 위해 다르게 사용한다.
@Service: 사용자의 요청이 들어오면 그 요청에 맞는 서비스 제공하는 역할(더 세분화하면 @Requestmapping, @GetMapping, ...)
@Controller: 사용자의 입출력을 담당
@Repository(=DAO, 다오)
어노테이션 | 위치 | 의미 |
@Service | XXXServicelmpl | 비즈니스 로직을 처리하는 Service 클래스 |
@Repository | XXXDAO | 데이터베이스 연동을 처리하는 DAO 클래스 |
@Controller | XXXController | 사용자 요청을 제어하는 Controller 클래스 |
@Component 사용하기
아래와 같이 클래스 이름 위에 @Component 를 추가하면, (괄호 안의 값은 bean의 id)
@component("id")
class InlineExamConsole
{
@Autowired
public void setExam(Exam exam) {
this.exam = exam;
}
}
XML파일에 아래와 같은 bean 이 없어도, 자동으로 불러온다.
(@Autowired 위치에 따라 기본 생성자가 실행되거나, 특정 세터만 실행되거나 한다.)
<bean id="console" class="spring.di.ui.InlineExamConsole" >
</bean>
단, XML 파일의 위에 아래와 같은 코드가 추가되어 있어야 @Component를 사용할 수 있다.
스캔 하고 싶은 패키지 이름을 " " 안에 ,로 나열한다.
이 코드의 역할은
1. 어플리케이션 컨텍스트에 등록된 빈들의 어노테이션들이 적용될 수 있게 하고, 2. 000어노테이션이 설정된 새로운 빈들을 찾는 스캔도 할 수 있게 하는 것이다.
<context:component-scan base-package="spring.di.ui, spring.di.entity"/>
위 코드가 추가되어 있으면, @Component 어노테이션이 있는 객체는 자동으로 불러오므로,
Autowired가 필요한 객체가 있다는 것을 알려주는 아래 코드는 더 이상 필요가 없게 된다.
<context:annotation-config/>
'BackEnd > Spring' 카테고리의 다른 글
[Spring] AOP (0) | 2021.09.08 |
---|---|
[Spring] XML Configuration을 Java Configuration으로 변경하기 (0) | 2021.09.08 |
[Spring] @Autowired의 역할 (0) | 2021.08.30 |
[Spring] 이클립스에 Maven Repository 라이브러리 가져오기 (0) | 2021.08.28 |
[Spring] Application Context 작성하기 (0) | 2021.08.28 |
댓글