Spring에서 Bean 인스턴스가 생성된 이후 @Autowired
를 설정한 메서드가 자동으로 호출되고, 인스턴스가 자동으로 주입된다.
다음과 같이 Field에 @Autowired
를 적용할 수 있다.
@Service
@Transactional(readOnly = true)
public class MyService{
@Autowired
private MyRepository myRepository;
...
}
@Autowired
private UserService userService;
@Autowired
private PayService payService;
다음과 같이 Setter 적용시 의존성을 주입한다.
@Service
@Transactional(readOnly = true)
public class MyService {
private MyRepository myRepository;
@Autowired
public void setMyRepository(MyRepository myRepository) {
this.myRepository = myRepository;
}
...
}
가장 권장하는 방식입니다.
@Service
@Transactional(readOnly = true)
public class MyService {
private MyRepository myRepository;
@Autowired
public MyService(MyRepository myRepository) {
this.myRepository = myRepository;
}
...
}
@Autowired
가 필요없다. 생성자가 하나인 경우 자동으로 @Autowired
가 적용된다. 또한 MyRepository
는 더 이상 변경하지 않기 때문에 final
키워드를 추가한다.
@Service
@Transactional(readOnly = true)
public class MyService {
private final MyRepository myRepository;
public MyService(MyRepository myRepository) {
this.myRepository = myRepository;
}
...
}
@Service
@Transactional(readOnly = true)
@RequiredArgsConstructor
public class MyService {
private final MyRepository myRepository;
...
RequiredArgsConstructor
은 final
키워드만 있는 변수의 생성자를 생성한다.