Where to put @Bean in Spring Boot?

前端 未结 6 422
清歌不尽
清歌不尽 2020-12-24 05:32

I am wondering what the best place would be for a Spring Boot app to register additional beans. I have a Main class that is annotated with @SpringBootApplication

6条回答
  •  旧巷少年郎
    2020-12-24 05:50

    It depends on where the main class is located which has generally @SpringBootApplication annotations. You can annotate this main class with @ComponentScan(basePackageClasses = HelloWorld.class). Here HelloWorld has bean definitions annotated with @Beans and the class is annotated with @Configurations.

    Spring container will scan all the sub-packages of the class specified in @ComponentScan arguments. You can also give wild card entries instead of class name.

    Ex: 
    
    @SpringBootApplication
    @ComponentScan(basePackageClasses = HelloWorld.class)
    public class DemoApplication extends SpringBootServletInitializer {
    
         public static void main(String[] args) {
              SpringApplication.run(DemoApplication.class);
          }
    
    }
    
    **Bean Class:**
    
    @Configuration
    public class HelloWorld {
    
        @Bean
        public TweetUserSevice tweetUserSevice() {
            return new TweetUserSeviceImpl();
        }
    
    }
    

提交回复
热议问题