Spring Java-based容器配置
在Spring新的Java-configuration支持中,最核心的部分就是使用@Configuration注解的类和使用@Bean注解的类。
@Bean注解用于指示一个方法实例化。配置,初始化一个新的被Spring容器管理的对象。
springboot的自动配置
## 下来我们来一步步分析springboot的起步依赖与自动配置这两个核心原理
实际上重要的只有三个Annotation:
@Configuration(@SpringBootConfiguration里面还是应用了@Configuration)
@EnableAutoConfiguration
@ComponentScan
@Configuration的作用上面我们已经知道了,被注解的类将成为一个bean配置类。
@ComponentScan的作用就是自动扫描并加载符合条件的组件,比如@Component和@Repository等,最终将这些bean定义加载到spring容器中。
@EnableAutoConfiguration 这个注解的功能很重要,借助@Import的支持,收集和注册依赖包中相关的bean定义。
我们可以将自动配置的关键几步以及相应的注解总结如下:
1、@Configuration&与@Bean->基于java代码的bean配置
2、@Conditional->设置自动配置条件依赖
3、@EnableConfigurationProperties与@ConfigurationProperties->读取配置文件转换为bean。
4、@EnableAutoConfiguration、@AutoConfigurationPackage 与@Import->实现bean发现与加载。
如果要让一个普通类交给Spring容器管理,通常有以下方法:
1、使用 @Configuration与@Bean 注解
2、使用@Controller @Service @Repository @Component 注解标注该类,然后启用@ComponentScan自动扫描
3、使用@Import 方法
Configuration
@Import, @ImportResource
@Import
Indicates one or more {@link Configuration @Configuration} classes to import.
Composing @Configuration classes
With the @Import annotation

通过@Import将ImportSelector实现类, ImportBeanDefinitionRegister实现类, 注解@Configuration的类, 常规的component组件, 注册到bean工厂。
@ImportResource
Indicates one or more resources containing bean definitions to import.
<import resource="classpath:spring-config.xml" />
Reference:
- Composing XML-based configuration metadata
-
Resources (here the
classpath:
part is explained)
@ImportResource导入xml文件
@Import导入@Configuration文件
@Configuration:我们可以把它理解为Spring的xml配置文件中的<beans/>标签,也就是Spring容器的上下文
@Bean:我们可以把它理解为Spring的xml配置文件中的<bean/>标签,也就是用来注册一个bean的,我们可以配置initMethod、destroyMethod等注解属性来完成和<bean/>标签中对应属性配置一样的功能
@Scope:用来配置bean的作用域,默认是singleton,也就是单例
@ComponentScan:我们可以把它理解为Spring的xml配置文件中的<context:component-scan/>标签,也就是用来扫描@Component注解注册bean的,如果未指定包,则将从声明此注解的类的包进行扫描
@ImportResource:我们可以使用它来引入另一个Spring配置文件的配置
@Import:我们可以使用它来引入另一个注解配置
网友评论