我想访问应用程序中提供的值。属性,例如:
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("${property-name}") 应用程序。属性 @配置或@组件。
我尝试的另一种方法是用下面的方式创建一个Utility类来读取属性
protected PropertiesUtility () throws IOException {
properties = new Properties();
InputStream inputStream =
getClass().getClassLoader().getResourceAsStream("application.properties");
properties.load(inputStream);
}
您可以使用静态方法来获取作为参数传递的键的值。
其他回答
我也有这个问题。但是有一个很简单的解决办法。只需要在构造函数中声明你的变量。
我的例子:
application.propperties:
#Session
session.timeout=15
SessionServiceImpl经济舱:
private final int SESSION_TIMEOUT;
private final SessionRepository sessionRepository;
@Autowired
public SessionServiceImpl(@Value("${session.timeout}") int sessionTimeout,
SessionRepository sessionRepository) {
this.SESSION_TIMEOUT = sessionTimeout;
this.sessionRepository = sessionRepository;
}
尝试类属性loaderutils ?
这种方法不使用Spring引导的注释。传统的上课方式。
例子:
Resource resource = new ClassPathResource("/application.properties");
Properties props = PropertiesLoaderUtils.loadProperties(resource);
String url_server=props.getProperty("server_url");
使用getProperty()方法传递键并访问属性文件中的值。
属性中的@Value("${property-name}") 应用程序。属性 @配置或@组件。
我尝试的另一种方法是用下面的方式创建一个Utility类来读取属性
protected PropertiesUtility () throws IOException {
properties = new Properties();
InputStream inputStream =
getClass().getClassLoader().getResourceAsStream("application.properties");
properties.load(inputStream);
}
您可以使用静态方法来获取作为参数传递的键的值。
最简单的方法是使用Spring Boot提供的@Value注释。您需要在类级别定义一个变量。例如:
@ value (" $ {userBucket.path} ") private字符串userBucketPath
还有另一种方法可以通过环境类来做到这一点。例如:
自动装配环境变量到你的类,你需要访问这个属性:
@ autowired 私人环境环境
使用环境变量在你需要的行中获取属性值:
environment.getProperty(“userBucket.path”);
希望这能回答你的问题!
您可以使用@Value注释并访问您所使用的Spring bean中的属性
@Value("${userBucket.path}")
private String userBucketPath;
Spring Boot文档的Externalized Configuration部分解释了您可能需要的所有细节。