@Autowired 는 Spring Container 에서 관리 중인 Bean 을, 자료형이 같을 경우 자동 매핑해주는 어노테이션이다. 예제를 통해 알아보자.
예제는 ProductController 와 ProductService 로 구성되며,
ProductService 는 Interface 이고, ProductServiceImpl 내에 구현해놓았다.
ProductServiceImpl.java
@Service
public class ProductServiceImpl implements ProductService{
@Autowired
private SqlSession sqlSession;
...
}
주의해야 할 점은,
1. 생성자를 사용하면 안 된다.
@Controller
public class ProductController {
@Autowired
private ProductService productService = new ProductServiceImpl();
...
}
Controller 에서 생성자로 초기화해주면, 이는 Spring Container 에서 Singleton 으로 생성된 인스턴스를 참조하지 않고, 말 그대로 생성자로 인해 생성된 새로운 ProductServiceImpl 객체의 인스턴스를 참조한다.
이 경우 당연히 Null 은 뜨지 않겠지만, Spring Container 의 Bean 관리를 받는 것이 아니므로 DI 에 실패한 코드이다.
2. (내가 해결한 것) static 키워드를 사용하면 안 된다.
@Controller
public class ProductController {
@Autowired
private static ProductService productService; // 이 경우, 자동으로 생성자가 실행되지 않기 때문에 null 이다.
...
}
정적 멤버로 선언될 경우, ProductController 가 먼저 로드되고, ProductService 는 그 시점에서 생성되지 않기 때문이다.
잘 모르겠다면 static autowired 로 검색해보자.
최근댓글