@Value 可以给字段赋值
背景
@Value通常与@PropertySource(value = “db.properties”) 组合使用读取配置注入参数,那如果我们的值是其它存储,如何才能自动赋值
实现原理
实现很简单
//自动注入此对象
@Autowired
private Environment environment;
@PostConstruct
public void init() {
//拿到些对象
MutablePropertySources propertySources = ((ConfigurableEnvironment) this.environment).getPropertySources();
PropertySourceFactory factory = BeanUtils.instantiateClass(DefaultPropertySourceFactory.class);
//构造pathResource
PathResource pathResource = new PathResource("/Users/xx/soft/sp.properties");
try {
org.springframework.core.env.PropertySource<?> sd = factory.createPropertySource("sd", new EncodedResource(pathResource));
//设置值
propertySources.addFirst(sd);
} catch (IOException e) {
e.printStackTrace();
}
}
总结
主要是通过代码得到PropertySource 这个对象,然后得到environment这个对象,设置值就可以了