출처 : 코드로 배우는 스프링 웹 프로젝트 (구멍가게코딩단)
🚀 new Object( ) 처럼 직접적으로 객체를 생성하지 않더라도
스프링은 어노테이션 등의 방법으로 객체를 생성 및 관리할 수 있는
'컨테이너'기능을 가지고 있다.
- 스프링에서 관리되는 객체를 Bean이라고 한다.
- root-context.xml은 Bean 설정 파일이다.
<context:component-scan base-package="org.zerock.sample">
</context:component-scan>
🚀 @Setter와 @Autowired를 통한 의존성 주입 테스트
@Component
@Data
public class Chef {
}
@Component
@Data
public class Restaurant {
@Setter(onMethod_ = @Autowired)
private Chef chef;
/*
private Chef chef;
@Autowired
public void setChef(Chef chef){
}*/
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/main/webapp/WEB-INF/spring/root-context.xml")
public class SampleTests {
@Setter(onMethod_ = {@Autowired})
private Restaurant restaurant;
@Test
public void test() {
assertNotNull(restaurant);
assertNotNull(restaurant.getChef());
}
}
🚀 단일 생성자의 묵시적 자동 주입(스프링 4.3 버전 이후)
- 방금 전의 방법은 setter 주입
- 이제 볼 방법은 생성자 주입
@Component
@Data
public class Restaurant {
@Setter(onMethod_ = @Autowired)
private Chef chef;
}
@Component
@Data
@AllArgsConstructor
public class Restaurant {
private Chef chef;
}
@Component
@Data
public class Restaurant {
private Chef chef;
//@Autowired
public Restaurant(Chef chef){
this.chef = chef
}
}
@Component
@Data
@RequiredArgsConstructor
public class Restaurant {
@NonNull private Chef chef;
}
기존에는 생성자에서 @Autowired 등의 어노테이션을 추가했어야 하지만, 4.3이후에는 단일인 경우 묵시적으로 주입이 가능하다.
(생성자 2개 이상인 경우 어노테이션)
위 3개의 코드는 동일하게 작동한다.