为什么在@SpringBootApplication类中声明的bean已注册,即使它不是一个原型类?

时间:2016-09-12 19:35:41

标签: java spring spring-boot

我的项目中有这个主要课程

@SpringBootApplication
@EnableOAuth2Sso
public class App 
{
    public static void main(String[] args) throws Exception {
        SpringApplication.run(App.class, args);    
    }

    @Bean public RequestContextListener requestContextListener(){
        return new RequestContextListener();
    }

}

据我所知,如果我没有错误,组件扫描会扫描原型类中的bean,这些类是@Component, @Service, @Repository, @Controller之一。

来自春季文档

  

默认情况下,使用@Component,@ Repository,@ Service注释的类,   @Controller,或者自己注释的自定义注释   @Component是唯一检测到的候选组件。

我无法理解这个类中的bean是如何注册的。因为它不是一个刻板的类,并且没有使用@Component注释注释,所以它不应该首先被扫描,但是这个代码完美地工作。事实上,对于我在这个类中使用bean的用例是解决问题的唯一方法,但这是另一回事。任何人都可以解释一下。谢谢!!

2 个答案:

答案 0 :(得分:5)

@SpringBootApplication是一个元注释,如下所示:

// Some details omitted
@SpringBootConfiguration
@EnableAutoConfiguration
public @interface SpringBootApplication { ... }

@SpringBootConfiguration也是元注释:

// Other annotations
@Configuration
public @interface SpringBootConfiguration { ... }

@Configuration是:

// Other annotations
@Component
public @interface Configuration { ... }

它起作用了:

  

默认情况下,使用@Component,@ Repository,@ Service注释的类,   @Controller,或自己注释的自定义注释   @Component是唯一检测到的候选组件。

答案 1 :(得分:2)

这是因为@SpringBootApplication也充当@Configuration注释。

@Configuration用于在xml spring configurarion文件中创建定义bean。

您可以拥有bean配置类。

@Configuration
class MyConfiguration{
@bean MyBean myBean(){...};
}

o您可以拥有Spring配置文件

<beans>
   <bean id="myBean" class="MyBean" />
</beans>

在您的情况下,当您使用@SpringBootApplication

时,您正在使用Spring配置类

你可以在这里看到更多

http://www.tutorialspoint.com/spring/spring_java_based_configuration.htm

http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/autoconfigure/SpringBootApplication.html

http://docs.spring.io/spring/docs/4.2.1.RELEASE/javadoc-api/org/springframework/context/annotation/Configuration.html