
ApplicationContext 가 빈을 찾아 주입한다. @Autowired — 타입 기반 주입주입 방식
필드 주입: 간단하지만 테스트/불변성에 약함.
@Service
public class BookService {
@Autowired private BookDAO bookDAO;
}
생성자 주입(권장): 의존성 보장, 불변성 확보, 테스트 용이. 생성자가 하나면 생략해도 동작.
@Service
public class BookService {
private final BookDAO bookDAO;
@Autowired
public BookService(BookDAO bookDAO){ this.bookDAO = bookDAO; }
}
세터 주입: 선택적 의존성이나 프레임워크 바인딩에 유용.
@Service
public class BookService {
private BookDAO bookDAO;
@Autowired public void setBookDAO(BookDAO dao){ this.bookDAO = dao; }
}
컨테이너 부팅/스캔
ApplicationContext ctx =
new AnnotationConfigApplicationContext("com.ohgiraffers.section01");
@Primary — 우선 빈 지정@Component @Primary
public class Charmander implements Pokemon { ... }
@Qualifier — 이름으로 특정@Service
public class PokemonService {
@Autowired @Qualifier("pikachu")
private Pokemon pokemon;
}
@Qualifier 가 @Primary 보다 우선한다. @Service
public class PokemonService {
private final List<Pokemon> list;
private final Map<String, Pokemon> map;
@Autowired
public PokemonService(List<Pokemon> list) { this.list = list; }
@Autowired
public PokemonService(Map<String, Pokemon> map) { this.map = map; }
}
List/Map 에 담긴다. @Resource (javax.annotation)@Service
public class PokemonService {
@Resource(name = "pikachu")
private Pokemon pokemon; // 이름으로 주입, 없으면 타입으로
}
@Inject (javax.inject) + @Named@Service
public class PokemonService {
private final Pokemon pokemon;
@Inject
public PokemonService(@Named("pikachu") Pokemon pokemon) {
this.pokemon = pokemon;
}
}
@Named("name") 로 지정. @Qualifier: 동일 타입 다수 빈 환경의 기본 선택지.@Primary: 글로벌 기본값처럼 쓰고, 필요 시 @Qualifier 로 덮어쓴다.@Resource, @Inject 도입. | 구분 | 제공 | 지원 방식 | 빈 탐색 우선순위 | 특정 빈 지정 | |
|---|---|---|---|---|---|
@Autowired | Spring | 필드, 생성자, 세터 | 타입 → 이름 | @Qualifier("name") | |
@Resource | Java | 필드, 세터 | 이름 → 타입 | @Resource(name="name") | |
@Inject | Java | 필드, 생성자, 세터 | 타입 → 이름 | @Named("name") |
컨텍스트 부팅
new AnnotationConfigApplicationContext("com.ohgiraffers.section02");
동일 타입 충돌 해결
@Primary class A implements T {}
@Component @Qualifier("b") class B implements T {}
리스트/맵 주입 후 실행
list.forEach(T::run);
map.forEach((k,v)->v.run());
@Qualifier 로 정확히 지정하고 전역 기본은 @Primary 로 둔다. 필요 시 컬렉션 주입과 표준 애노테이션(@Resource, @Inject)을 조합해 상황에 맞게 선택한다.