새소식

반응형
Java/Spring Boot

@Autowired 와 @Resource 차이점

  • -
728x90
반응형

두개의 어노테이션은 Spring 컨테이너가 Spring 컨테이너에 등록되어 있는 Bean 객체를 찾아 자동으로

의존성을 주입해준다.

 

@Autowired

 

Bean 객체 찾는 순서

타입 > 이름 > @Qualifier > 실패

 

@Autowired 는 주입하려고 하는 객체의 타입을 확인해 컨테이너에서 Bean 객체를 찾는다.

만약 타입이 존재하지 않으면 @Autowired 에 설정된 이름으로 Bean 객체를 찾고 이름이 없을 경우

@Qualfier 어노테이션 유무를 찾아 주입한다. 없을 경우 예외가 발생한다.

 

생성자, 필드, 메서드 모두 적용 가능하다.

 

Spring Boot 가 아닌 Spring 프레임워크일 경우 xml 설정 파일에 <context:annotation-config/> 구문을 넣어준다.

 

@Service
public class UserDetailsServiceCustom implements UserDetailsService {
	
	@Autowired
	UserInfoService userInfoService;
    
   	...
}

 

userInfoService 라는 필드명은 UserInfoService 클래스 타입Bean 객체의존성을 갖는다.

 

@Resource

Bean 객체 찾는 순서

이름 > 타입 > @Qualifier > 실패

 

@Resource 의 name 속성 이름을 기준으로 Bean 객체를 찾아 의존 주입을 한다.

name 속성 설정이 없을 경우 객체 타입으로 찾고 없으면 @Qualifier 어노테이션 설정 유무로 찾아 의존주입을 한다.

 

@Autowired 와 같이 Spring 프레임워크일 경우 xml 설정 파일에 <context:annotation-config />  구문을 넣어준다.

 

타입, 필드, 메서드에 적용 가능하다.

 

// userInfoService 라는 이름의 Bean 객체
@Service("testUserInfoService")
public class UserInfoService {
	private final SqlSessionTemplate sqlSession;
	
	public UserInfoService(SqlSessionTemplate sqlSession) {
		this.sqlSession = sqlSession;
	}
	
	public UserData userDataInfo(String username) {
		UserInfoMapper mapper = sqlSession.getMapper(UserInfoMapper.class);
		
		return mapper.userData(username);
	}
}

@Service
public class UserDetailsServiceCustom implements UserDetailsService {
	
	@Resource(name="userInfoService")
	UserInfoService userInfoService;
    
    ....
}

 

userInfoService 라는 필드명은 testUserInfoService이름을 가진 Bean 객체에 의존성을 갖고 있다.

728x90
반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.