개인 공부 (23.07~
Spring Bean 등록 방법 (@Component, @Configuration + @Bean)
Song쏭
2023. 8. 5. 00:06
▶등록 방법1
@Component 활용
@Component
public class ProductService {
ProductService() {
System.out.println("ProductService 객체 생성");
}
}
▶등록 방법2
@Configuration + @Bean 활용
(ProductService 클래스에서 @Component는 없앤 상태로)
@Configuration
public class AppConfig {
@Bean
public ProductService productService() {
return new ProductService();
}
}
▶만약 등록 방법을 둘 다 사용하여 프로젝트를 실행시켰을 시,
아래의 에러가 뜬다.
이미 같은 이름을 가진 bean이 존재한다고 오류를 보내주고 있다. 똑똑하다..
bean의 이름을 바꾸거나 오버라이딩을 가능하게끔 셋팅하라고 조치방안을 안내해준다..
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2023-08-04 23:59:00.279 ERROR 34436 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
The bean 'productService', defined in class path resource [com/example/demo/AppConfig.class],
could not be registered. A bean with that name has already been defined in file [C:\DEV\java\intellij-ulti-workspace\demo\build\classes\java\main\com\example\demo\ProductService.class]
and overriding is disabled.
Action:
Consider renaming one of the beans
or enabling overriding by setting spring.main.allow-bean-definition-overriding=true
Process finished with exit code 1