본문 바로가기
Programming/Spring

[spring] Annotation 기반 설정

by NAMP 2016. 4. 20.

[spring] Annotation 기반 설정

bean 태그를 기술하지 않고 어노테이션을 사용한다.
컴파일을 해도 사라지지 않는 주석

@Component
public class UserDAO_JDBC implements UserDAO {...}

Bean 태그를 대신하는 @Component 를 넣는다.
클래스명에서 첫글자를 소문자로 바꾼 것이 기본이름으로 들어간다.

@Component(“userDAO_JDBC”)

@Component 로 마킹함으로써 모두 메모리에 올라가게 된다.

이름을 부여한다.

@Component("service")
public class UserServiceImpl implements UserService { … }

Annotation 설정

Namespace 선언

Component 스캔

applicationContext.xml 파일 수정


context 체크

<context:component-scan base-package="user" />

스캔 대상의 경우 아이콘에 S 가 표시된다.

과 관련된 Annotation

클래스를 XML 파일에 태그로 등록하여 Spring Framework 에 의해 관리되는 클래스로 등록하는 것을 대체하기 위한 Annotation 은 @Service, @Component 다.

@Repository 은 DAO 같은 데이터 접근 로직을 처리해주는 클래스를 위한 어노테이션이다.
Persistence Layer 에서 발생한 Exception 에 대한 Transaction 처리부분이 추가된 어노테이션이다.

어노테이션을 변경한다.
Component → Service
Component → Repository

@Service("service")
public class UserServiceImpl implements UserService {

@Repository("ibatis")
public class UserDAO_iBatis implements UserDAO {

Dependency Injection 설정

Dependency Injection 관련 Annotation

@Autowired Annotation

Spring 프레임워크에서 지원하는 Dependency 정의 용도의 Annotation
Spring 프레임워크에 종속적
정밀한 Dependency Injection 이 필요한 경우에 유용

@Autowired 는 Spring2.5 버전 이후에 추가도니 기능
타입을 기반으로 의존관계에 있는 객체를 주입

    @Autowired
    private UserDAO dao;

dao 에 값을 입력한다.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'service': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private user.dao.UserDAO user.service.UserServiceImpl.dao; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [user.dao.UserDAO] is defined: expected single matching bean but found 4: ibatis,jdbc,mybatis,spring

동일 타입이 있으므로 에러 발생

byName 으로 변경해야 함

@Qualifier

동일한 타입의 Bean 객체가 여러 개 있는 경우에 특정 Bean 객체를 선택적으로 주입할 때 사용

    @Autowired
    @Qualifier("ibatis")
    private UserDAO dao;

@Resource Annotation

JSR-250 표준 Annotation 으로 Spring Framework 2.5 이 후 버전부터 지원하는 Annotation 으로서 특정 프레임워크에 종속되지 않는 Annotation 이다.

    @Resource(name="jdbc")
    private UserDAO dao;


댓글