
ConfilictAppConfig
@Configuration
public class ConflictAppConfig {
// conflictService 이름으로 Bean 생성
@Bean(name = "conflictService")
MyService myService() {
return new ConflictServiceV2();
}
}
ConflictApp2
@ComponentScan(basePackages = "com.example.springconcept.conflict2")
public class ConflictApp2 {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(ConflictApp2.class);
// Service 빈을 가져와서 실행
MyService service = context.getBean(MyService.class);
service.doSomething();
}
}
ConflictService
@Component
public class ConflictService implements MyService {
@Override
public void doSomething() {
System.out.println("ConflictService 메서드 호출");
}
}
ConflictServiceV2
public class ConflictServiceV2 implements MyService {
@Override
public void doSomething() {
System.out.println("ConflictServiceV2 메서드 호출");
}
}
ConflictApp2를 실행할 경우 수동으로 등록한 bean인 ConflictServiceV2의 메서드가 실행된다.
그 이유는 수동으로 등록한 빈이 자동 등록 빈을 오버라이딩하여 우선권을 가지기 때문이다.
Spring Boot에서는 수동과 자동 Bean등록의 충돌이 발생하면 오류가 발생한다.
하지만 application.properties에서 설정을 변경하면 둘이 충돌시 위와 같이 자동 오버라이딩하여 수동으로 등록한 빈이 우선권을 가지게 할 수 있다.
// 수동, 자동 Bean을 동시에 등록할 때 이름이 같으면 수동 Bean이 오버라이딩
spring.main.allow-bean-definition-overriding=true
// 기본값
spring.main.allow-bean-definition-overriding=false'spring' 카테고리의 다른 글
| 같은 타입의 Bean 충돌 해결(@Qualifier @Primary) (0) | 2025.02.04 |
|---|---|
| 의존관계 주입 / @RequiredArgsConstructor (0) | 2025.02.04 |
| MVC와 템플릿 엔진, API (0) | 2025.01.31 |
| View 환경설정 (3) | 2025.01.31 |
| @Controller 랑 @RestController 차이점 (0) | 2025.01.23 |