我想访问应用程序中提供的值。属性,例如:
logging.level.org.springframework.web: DEBUG
logging.level.org.hibernate: ERROR
logging.file=${HOME}/application.log
userBucket.path=${HOME}/bucket
我想访问userBucket。在Spring Boot应用程序的主程序中的路径。
我想访问应用程序中提供的值。属性,例如:
logging.level.org.springframework.web: DEBUG
logging.level.org.hibernate: ERROR
logging.file=${HOME}/application.log
userBucket.path=${HOME}/bucket
我想访问userBucket。在Spring Boot应用程序的主程序中的路径。
当前回答
有两种方法,
你可以直接在类中使用@Value
@Value("#{'${application yml field name}'}")
public String ymlField;
OR
要使它干净,你可以清除@Configuration类,在那里你可以添加所有的@value
@Configuration
public class AppConfig {
@Value("#{'${application yml field name}'}")
public String ymlField;
}
其他回答
您可以使用@Value注释并访问您所使用的Spring bean中的属性
@Value("${userBucket.path}")
private String userBucketPath;
Spring Boot文档的Externalized Configuration部分解释了您可能需要的所有细节。
对我来说,以上这些方法对我都没有直接作用。 我所做的是:
另外,我补充了@Rodrigo Villalba Zayas的回答 实现InitializingBean到类 并实现了该方法
@Override
public void afterPropertiesSet() {
String path = env.getProperty("userBucket.path");
}
这看起来就像
import org.springframework.core.env.Environment;
public class xyz implements InitializingBean {
@Autowired
private Environment env;
private String path;
....
@Override
public void afterPropertiesSet() {
path = env.getProperty("userBucket.path");
}
public void method() {
System.out.println("Path: " + path);
}
}
应用程序。Yml或application.properties
config.value1: 10
config.value2: 20
config.str: This is a simle str
MyConfig类
@Configuration
@ConfigurationProperties(prefix = "config")
public class MyConfig {
int value1;
int value2;
String str;
public int getValue1() {
return value1;
}
// Add the rest of getters here...
// Values are already mapped in this class. You can access them via getters.
}
任何想要访问配置值的类
@Import(MyConfig.class)
class MyClass {
private MyConfig myConfig;
@Autowired
public MyClass(MyConfig myConfig) {
this.myConfig = myConfig;
System.out.println( myConfig.getValue1() );
}
}
属性中的@Value("${property-name}") 应用程序。属性 @配置或@组件。
我尝试的另一种方法是用下面的方式创建一个Utility类来读取属性
protected PropertiesUtility () throws IOException {
properties = new Properties();
InputStream inputStream =
getClass().getClassLoader().getResourceAsStream("application.properties");
properties.load(inputStream);
}
您可以使用静态方法来获取作为参数传递的键的值。
另一种方法是将org.springframework.core. environment注入到bean中。
@Autowired
private Environment env;
....
public void method() {
.....
String path = env.getProperty("userBucket.path");
.....
}