settings -->f" />

飞道的博客

springBoot系列常用注解

241人阅读  评论(0)

@PropertySource

作用是:对自定义的properties文件加载

使用:@PropertySource(value={"classpath:people.properties"})或者@PropertySource(value="classpath:people.properties")

properties文件,获取到值乱码问题

乱码解决:

file ->settings -->file encoding--> 勾选Transparent native-to-ascill conversion

@ImportResource

作用:可以让spring的配置文件生效

使用:在启用类上加ImportResource注解,如@ImportResource(value = "classpath:person.xml")或者@ImportResource(locations ={"classpath:person.xml"})

 

@Conditional

作用:必须是@Conditional指定的条件成立,才给容器中添加组件或者是让自动配置类生效

以 HttpEncodingAutoConfiguration 自动配置类举例


  
  1. @Configuration(proxyBeanMethods = false)
  2. @EnableConfigurationProperties(ServerProperties.class)
  3. @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
  4. @ConditionalOnClass(CharacterEncodingFilter.class)
  5. @ConditionalOnProperty(prefix = "server.servlet.encoding", value = "enabled", matchIfMissing = true)
  6. public class HttpEncodingAutoConfiguration {
  7. private final Encoding properties;
  8. public HttpEncodingAutoConfiguration(ServerProperties properties) {
  9. this.properties = properties.getServlet().getEncoding();
  10. }
  11. @Bean
  12. @ConditionalOnMissingBean
  13. public CharacterEncodingFilter characterEncodingFilter() {
  14. CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
  15. filter.setEncoding( this.properties.getCharset().name());
  16. filter.setForceRequestEncoding( this.properties.shouldForce(Encoding.Type.REQUEST));
  17. filter.setForceResponseEncoding( this.properties.shouldForce(Encoding.Type.RESPONSE));
  18. return filter;
  19. }

@ConditionalOnMissingBean:作用是如果容器中不存在CharacterEncodingFilter 这个bean则实例化创建一个,存在就不走下面的代码

@ConditionalOnClass(CharacterEncodingFilter.class):作用是如果容器中存在CharacterEncodingFilter 这个bean(其中一个条件)则才能够实例化者个自动配置类HttpEncodingAutoConfiguration 

@ConditionalOnProperty(prefix = "server.servlet.encoding", value = "enabled", matchIfMissing = true)作用是如果配置文件中配置了server.servlet.encoding=enabled则才能够实例化者这个个自动配置类HttpEncodingAutoConfiguration 

 

springBoot中所有的自动配置类位置:

org\springframework\boot\spring-boot-autoconfigure\2.4.5\spring-boot-autoconfigure-2.4.5.jar!\META-INF\spring.factories文件中

如何判断spring.factories这个文件中那些自动配置类是生效的?

在yml或者applicaton.properties中配置,会在控制台打印自动配置类生效报告:


  
  1. ########打印自动配置类生效的报告##########
  2. debug = true

其中:Negative match:表示未生效;Positive match:表示生效的

 


转载:https://blog.csdn.net/qq_38423256/article/details/115799792
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场