我想访问应用程序中提供的值。属性,例如:
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应用程序的主程序中的路径。
当前回答
最简单的方法是使用Spring Boot提供的@Value注释。您需要在类级别定义一个变量。例如:
@ value (" $ {userBucket.path} ") private字符串userBucketPath
还有另一种方法可以通过环境类来做到这一点。例如:
自动装配环境变量到你的类,你需要访问这个属性:
@ autowired 私人环境环境
使用环境变量在你需要的行中获取属性值:
environment.getProperty(“userBucket.path”);
希望这能回答你的问题!
其他回答
1.Injecting a property with the @Value annotation is straightforward:
@Value( "${jdbc.url}" )
private String jdbcUrl;
2. we can obtain the value of a property using the Environment API
@Autowired
private Environment env;
...
dataSource.setUrl(env.getProperty("jdbc.url"));
您可以使用@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);
}
}
为了从属性文件中选择值,我们可以有一个配置读取器类,比如ApplicationConfigReader.java 然后根据属性定义所有变量。参考下面的例子,
application.properties
myapp.nationality: INDIAN
myapp.gender: Male
下面是相应的阅读类。
@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "myapp")
class AppConfigReader{
private String nationality;
private String gender
//getter & setter
}
现在,我们可以在任何想要访问属性值的地方自动连接阅读器类。 如。
@Service
class ServiceImpl{
@Autowired
private AppConfigReader appConfigReader;
//...
//fetching values from config reader
String nationality = appConfigReader.getNationality() ;
String gender = appConfigReader.getGender();
}
有3种方法读取application.properties,
使用@Value, EnvironmentInterface和@ConfigurationProperties..
@Value(${userBucket.path})
private String value;
方式2:
@Autowired
private Environment environment;
String s = environment.getProperty("userBucket.path");
第三道:
@ConfigurationProperties("userbucket")
public class config {
private String path;
//getters setters
}
可以读取与getter和setter ..
参考资料-此处