본문 바로가기

spring/Annotation

@Autowired

@Autowired는 property injection을 위한 어노테이션이다.


스프링 설정파일에서 변수에 데이터나 객체를 주입해 주기 위한


<property> 태그를 대신해주는 어노테이션이라 할 수 있다.


<property> 태그는 해당 변수의 setter를 이용하여 속성 주입(property injection)을 한다면


autowired는 setter메소드에 사용해도 되고 변수에 직접 사용해도 된다.


예를 들어


아래와 같이 해줘도 되지만


private Sender sender;


@Autowired

public void setkbs(Sender sender) { //Autowired로 설정할 메소드 이름은 중요하지 않다.

this.sender = sender;

}


아래와 같은 경우도 가능하며 더 간편하다. 실제로 권장하는 방법


@Autowired

private Sender sender;


Autowired는 해당 객체변수의 타입의 Component(Service, Controller, Repository 어노테이션으로 설정된 객체, 혹은 설정파일에서 만들어진 객체) 객체를 찾아서 맴핑한다.


예를들어


@Autowired

private Sender sender;


해줬다면 


Sender class의 객체를 찾아서 맵핑한다.


설정파일에서


<bean id="sender1" class="pack.Sender"/>


라든지


자바에서 어노테이션을 이용한 객체생성


@Commponent

public class Sender{

}


스프링이 만들어 놓은 같은 타입의 객체를 맵핑한다.


추가로 @Autowired(required=false) 설정 부분이 있는데


@Required 기능과 똑같고 만약에 프로퍼티를 반드시 설정하지 않아도 된다면 false라고 명시하고 만약 명시하지 않으면 기본값 true로 설정된다.


'spring > Annotation' 카테고리의 다른 글

@Value, Spring EL  (0) 2014.05.07
@Resource  (0) 2014.05.02
어노 테이션을 사용하기 위한 설정  (0) 2014.05.02
@component : @Service,@Repository,@Controller  (0) 2014.05.02
@Required  (0) 2014.05.02