@SpringBootApplicationpublicclassDemoApplication {// 아래에서 추가한 빈을 이렇게 사용할 수도 있다. @AutowiredMyService myService;publicstaticvoidmain(String[] args) {// java 10 부터 추가된 var 타입var app =newSpringApplication(DemoApplication.class);// 만약 중간에 작업을 추가하고 싶다면 아래 내용을 추가한다.// 이 Initializer는 내가 원하는 애플리케이션 컨텍스트를 주입받을 수 있다.app.addInitializers((ApplicationContextInitializer<GenericApplicationContext>) ctx -> {// 이 GenericApplicationContext을 가지고 직접 원하는 빈을 등록한다.ctx.registerBean(MyService.class);ctx.registerBean(ApplicationRunner.class, () -> args1->System.out.println("Functional Bean Definition!!")); });// 애플리케이션 실행 코드app.run(args); }}
2020-03-16 20:41:42.916 INFO 19515 --- [ main] m.w.componentscan.DemoApplication : Starting DemoApplication on macbook.local with PID 19515 (/Users/sojeong/dev/IntelliJ-workspace/spring-keesun-baik/spring-framework-core-03-component/target/classes started by sojeong in /Users/sojeong/dev/IntelliJ-workspace/spring-keesun-baik)
2020-03-16 20:41:42.918 INFO 19515 --- [ main] m.w.componentscan.DemoApplication : No active profile set, falling back to default profiles: default
2020-03-16 20:41:43.428 INFO 19515 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-03-16 20:41:43.434 INFO 19515 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-03-16 20:41:43.435 INFO 19515 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.31]
2020-03-16 20:41:43.471 INFO 19515 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-03-16 20:41:43.472 INFO 19515 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 526 ms
class me.whiteship.componentscan.MyBookRepository
2020-03-16 20:41:43.571 INFO 19515 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-03-16 20:41:43.717 INFO 19515 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-03-16 20:41:43.721 INFO 19515 --- [ main] m.w.componentscan.DemoApplication : Started DemoApplication in 1.028 seconds (JVM running for 6.788)
Functional Bean Definition!!
이렇게 하면 조건문 등 원하는 코드를 사이에 집어넣을 수 있다는 장점이 있다. 하지만 일일이 등록해야 하므로 컴포넌트 스캔을 대체하는 것은 힘들다.
동작 원리
실제 스캐닝은 ConfigurationClassPostProcessor라는 BeanFactoryPostProcessor에 의해 처리된다.