我想访问应用程序中提供的值。属性,例如:
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应用程序的主程序中的路径。
当前回答
应用程序。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注释并访问您所使用的Spring bean中的属性
@Value("${userBucket.path}")
private String userBucketPath;
Spring Boot文档的Externalized Configuration部分解释了您可能需要的所有细节。
应用程序可以从应用程序中读取3种类型的值。属性文件。
application.properties
my.name=kelly
my.dbConnection ={connection_srting:'http://localhost:...',username:'benz',password:'pwd'}
类文件
@Value("${my.name}")
private String name;
@Value("#{${my.dbConnection}}")
private Map<String,String> dbValues;
如果你在申请中没有房产。属性,则可以使用默认值
@Value("${your_name : default value}")
private String msg;
可以使用@Value注释从应用程序中读取值。属性/ yml文件。
@Value("${application.name}")
private String applicationName;
另一种方法是将org.springframework.core. environment注入到bean中。
@Autowired
private Environment env;
....
public void method() {
.....
String path = env.getProperty("userBucket.path");
.....
}
@ value (" $ {userBucket.path} ") private String userBucketPath;