自己实现建了一个切面注解@Mypoint
注解有一个key属性
String key();
在使用注解时
@Mypoint(key = "abc-${env}")
在properties配置文件中有
env=dev
这样通过配置文件可以动态切换注解中jKey的值
情况介绍:
这个切面注解是我引用的别人包里的,所以这个注解里的内容和功能我是没法改的,我只是想通过配置文件动态修改注解中的key值,在不同环境中给他传不同的值。
##解决过程
通常都会用@Value注解中使用${}获取properties中的参数值,在网上搜的大部分也都是说的是这个。
我自己以前尝试后在@PropertySource注解中使用
@PropertySource(value = "classpath:config-${spring.profiles.active}.yml")
这个在spring boot中使用时可行的,但是自己写的不起作用
可能有spring内部的原理没搞清楚,希望有尝试过的能提供一些建议,谢谢!!!
12-4号补充
一楼的回答我尝试了,但是不是我想要的方式,可能我的描述有遗漏,所以对问题做了一些补充。
新建ClientEnvironmentPostProcessor类实现EnvironmentPostProcessor,ServletContextListener接口
在postProcessEnvironment方法中写
String[] activeProfiles = environment.getActiveProfiles();
ProfilesBean profilesBean = ProfilesBean.getInstance();
profilesBean.setProfiles(activeProfiles[0]);
debug发现activeProfiles[0]就是你所需要的dev或者pro了
public class ProfilesBean {
//饿汉单例模式
//在类加载时就完成了初始化,所以类加载较慢,但获取对象的速度快
private static ProfilesBean profilesBean = new ProfilesBean();//静态私有成员,已初始化
private String profiles;
private ProfilesBean()
{
//私有构造函数
}
public static ProfilesBean getInstance() //静态,不用同步(类加载时已初始化,不会有多线程的问题)
{
return profilesBean;
}
public String getProfiles() {
return profiles;
}
public void setProfiles(String profiles) {
this.profiles = profiles;
}
}
最后在系统每处都可以用ProfilesBean.getInstance().getProfiles() 获取