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