Spring注解驱动

Bean的定义:XML配置文件与注解

@Configuration

作用: 相当于XML文件的beans标签;
使用范围:

@Configuration can be considered the equivalent of XML’s <beans/> element. Like <beans/>, it provides an opportunity to explicitly set defaults for all enclosed bean definitions.

@Import

作用: 等价于XML文件的import标签,导入一个或多个@Configuration类;
使用范围: 类,与@Configuration配合使用;

Often it is preferable to use an aggregation approach, where one @Configuration class logically imports the bean definitions defined by another.The @Import annotation provides just this kind of support, and it is the direct equivalent of the <import/> element found in Spring beans XML files.

@Bean

作用: 等价于XML文件的bean标签,用于定义bean;
使用范围: 方法,通常与@Configuration配合使用;

Typically, @Bean methods are declared within @Configuration classes. In this case, bean methods may reference other @Bean methods in the same class by calling them directly. This ensures that references between beans are strongly typed and navigable. Such so-called ‘inter-bean references’ are guaranteed to respect scoping and AOP semantics, just like getBean() lookups would. These are the semantics known from the original ‘Spring JavaConfig’ project which require CGLIB subclassing of each such configuration class at runtime. As a consequence, @Configuration classes and their factory methods must not be marked as final or private in this mode.

Spring注解驱动

属性的配置:属性文件与注解

@PropertySource

作用: 添加属性配置文件到Spring容器;
使用注意: 与@Configuration配合使用;

@Value

作用: 给Bean的单个属性赋值;
使用范围: 属性、方法或构造函数的入参;

@ConfigurationProperties

作用: 给Bean的多个属性批量赋值;
使用范围: 类或者在@Configuration类中被@Bean标注的方法;
使用注意:

  1. 添加@EnableConfigurationProperties,使SpringBoot支持@ConfigurationProperties;
  2. 属性必须有setter方法;
  3. 默认会从application.xml查找属性值,可以使用@PropertySource指定特定的文件;

@EnableConfigurationProperties

作用: 开启对@ConfigurationProperties的支持;
Spring注解驱动
参考:

  1. @Configuration官方示例:https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/Configuration.html;
  2. @Bean官方示例:https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/Bean.html;
  3. @Bean官方示例:https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/PropertySource.html;