spring boot 注解说明

Starters

可以创建自己的Starter,但名字格式不能是 spring-boot-starter-*,而是 *-spring-boot-starter。类似Maven插件的规则。
 

自动配置

@Import 和 @ComponentScan 类似;
@EnableAutoConfiguration 和 @SpringBootApplication 类似;---注意,只能使用一次,建议用在primary @Configuration class上。
 
注意,自动配置永远是第二位的,一旦你配置自己的东西,那自动配置的就会被覆盖。
查看自动配置都配置了什么,以及为什么,启动应用的时候加上 --debug即可。
禁用特定的自动配置:
import org.springframework.boot.autoconfigure.*;
import org.springframework.boot.autoconfigure.jdbc.*;
import org.springframework.context.annotation.*;
@Configuration
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class MyConfiguration {
}
如果class不在classpath中,可以使用 excludeName,然后使用全路径即可。
 

@SpringBootApplication

@SpringBootApplication 等同于默认的属性的 @Configuration@EnableAutoConfiguration and @ComponentScan。 
-- 注意,@ComponentScan 不能凭空使用。

类型安全的Configuration Properties

这里的意思是说,通过Java类来确保类型安全,但值还是要在YAML中提供!!

做为配置文件的对象类

@ConfigurationProperties(prefix="connection")
public class ConnectionProperties {
    private String username;
    private InetAddress remoteAddress;
    // ... getters and setters
}
那么,@Value("${property}")  和@ConfigurationProperties 的区别? 暂略。
注意:通过 @ConfigurationProperties 类进行的properties设置,需要在 @Configuration 类上开启 @EnableConfigurationProperties 注解才行,
而且,需要手动添加 @ConfigurationProperties 类,
如下:
用@Configuration注解该类,等价 与XML中配置beans;用@Bean标注方法等价于XML中配置bean。
@Configuration
@EnableConfigurationProperties(ConnectionProperties.class)
public class MyConfiguration {
}
需要注意的是, @ConfigurationProperties 类对应的bean有一个约定好的名字: <prefix>-<fqn> 。fqn是full qualified name。
前面的例子,对应的名字是: connection-com.example.ConnectionProperties ,这里假定它在包 com.example 中。
但是,@ConfigurationProperties 类对应的bean还有一个默认的名字!!!只是,不建议在environment之外使用而已。

 由于 @EnableConfigurationProperties 注解 会被自动应用到项目中,所以,只要确保 @ConfigurationProperties 类 是一个bean(即@Component),就会被自动添加到 Environment 。如下:

@Component //确保是一个bean即可!
@ConfigurationProperties(prefix="connection")
public class ConnectionProperties {
    // ... getters and setters of username and remoteAddress, and so on
}

Profiles

@Profile 可以用于 @Component 或 @Configuration 。
 

 

 

 

 

posted @ 2017-01-25 16:46  张建斌  阅读(785)  评论(0编辑  收藏  举报