0
在属性文件(config.properties)我定义几个属性:解决@Value失败 - 弹簧的java
my.property.first=xyz
my.property.second=12
我创建了一个类来读取这些属性:
package my.package.first;
............
@Configuration
public Class MyProperties {
@Value("${my.property.first}") private String propertyFirst;
@Value ("${my.property.second}") private String propertySecond;
public String getPropertyFirst() {
return propertyFirst;
}
public int getPropertySecond() {
return propertySecond
}
@Bean
public MyProperties getInstance() {
return this;
}
}
现在我想放在一些其他包中的类来使用这些属性:
package my.otherpackage.third;
import my.property.package.first.MyProperties;
.............................
public class GetMyProperties{
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyProperties.class);
MyProperties myProperties =context.getBean("getInstance",MyProperties.class);
//This returns ${my.property.first}
String propertyFirst = myProperties.getPropertyFirst();
// This returns ${my.property.second}
int propertySecond = context.getBeanFactory().resolveEmbeddedValue(("${my.property.first}"));
}
我尝试溶胶通过仅使用注释来实现这一点。
我使用Spring 4
感谢
我增加了豆的getInstance()只是为了得到myProperties实例。如果我删除此bean,如何访问类GetMyProperties中的属性? – uztrew
在另一个地方定义bean,你的bean不能同时配置和bean。无论Spring在何处定义bean(只要它在配置类中),它都会在你的应用程序中有\\ComponentScan或\ @SpringBootApplication的地方选择它,而我很确定你做到了。 – user2323354
我的意思是有没有一种方法来访问这些属性而根本不使用这个bean? – uztrew