@PropertySource注解@Value注解

@PropertySource注解@Value注解,第1张

@PropertySource注解@Value注解

@PropertySource遇到的坑
  • 配置文件
  • 处理方法

配置文件

当项目的配置文件外置了(比如放入nacos统一管理了),就不要再在类上面使用此注解,不然会报错:class path resource [XXX.properties] cannot be opened because it does not exist

处理方法

去掉此注解,如果该类下面需要获取配置文件的内容,直接使用@Value("${XXX}")就可以。
注意
在配置类中使用此注解可能会获取不到值,如下图
![在这里插入图片描述](https://img-blog.csdnimg.cn/aa3d33d12a14413f984413120691975.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAamF2YV9mYXll,size_20,color_FFFFFF,t_70,g_se,x_16
解决方案:
注册 PropertySourcesPlaceholderConfigurer
在没有 xml 配置的 Spring 应用程序中,PropertySourcesPlaceholderConfigurer必须在所有应用程序上下文中注册一个静态bean。
要注册,PropertySourcesPlaceholderConfigurer只需将相同类型的静态 bean 与您想要访问的属性源一起添加到配置中。要导入多个属性源,请使用@PropertySources注释(Java 8 之前)或多个@PropertySource注释(Java 8)。如下图

或者
@Configuration
@ComponentScan
class ApplicationConfig {

@Bean
public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
    PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
    configurer.setLocation(new ClassPathResource("application_dev.properties"));
    return configurer;
}

}

注意:下面针对spring+shiro情况讲解(其他情况可能也可以以类似的方法解决)
在spring整shiro时会创建LifecycleBeanPostProcessor的bean,LifecycleBeanPostProcessor是Bean的后置处理器,它的初始化比一般的bean初始化要早,所以如果LifecycleBeanPostProcessor bean放在@Configuration配置文件中,并且还和其他的普通bean放在一个目录下就会导致bean加载的一些问题。
解决方法有两个:
1、使用static方法注册后置处理器
2、LifecycleBeanPostProcessor单独在一个@Configuration配置文件中
我使用的是第一种

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5681093.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-17
下一篇2022-12-17

发表评论

登录后才能评论

评论列表(0条)

    保存