Java 如何在Spring Boot中访问application.properties文件中定义的值
我想访问Java 如何在Spring Boot中访问application.properties文件中定义的值,java,spring-boot,properties-file,Java,Spring Boot,Properties File,我想访问应用程序中提供的值。属性,例如: logging.level.org.springframework.web: DEBUG logging.level.org.hibernate: ERROR logging.file=${HOME}/application.log userBucket.path=${HOME}/bucket 我想在Spring Boot应用程序中访问主程序中的userBucket.path。您可以使用@Value注释并访问正在使用的任何Spring bean中的属
应用程序中提供的值。属性
,例如:
logging.level.org.springframework.web: DEBUG
logging.level.org.hibernate: ERROR
logging.file=${HOME}/application.log
userBucket.path=${HOME}/bucket
我想在Spring Boot应用程序中访问主程序中的
userBucket.path
。您可以使用@Value
注释并访问正在使用的任何Spring bean中的属性
@Value("${userBucket.path}")
private String userBucketPath;
Spring引导文档的这一部分解释了您可能需要的所有细节。另一种方法是将
org.springframework.core.env.env.Environment
注入到您的bean中
@Autowired
private Environment env;
....
public void method() {
.....
String path = env.getProperty("userBucket.path");
.....
}
@ConfigurationProperties
可用于将值从.properties
(.yml
也受支持)映射到POJO
考虑下面的示例文件
.properties
cust.data.employee.name=Sachin
cust.data.employee.dept=Cricket
config.value1: 10
config.value2: 20
config.str: This is a simle str
@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() );
}
}
Employee.java
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@ConfigurationProperties(prefix = "cust.data.employee")
@Configuration("employeeProperties")
public class Employee {
private String name;
private String dept;
//Getters and Setters go here
}
现在,可以通过自动关联employeeProperties
访问属性值,如下所示
@Autowired
private Employee employeeProperties;
public void method() {
String employeeName = employeeProperties.getName();
String employeeDept = employeeProperties.getDept();
}
如果要在一个位置使用此值,可以使用
@Value
从应用程序.properties
加载变量,但如果需要更集中的方式加载此变量,则@ConfigurationProperties
是更好的方法
此外,如果需要不同的数据类型来执行验证和业务逻辑,则可以加载变量并自动强制转换
application.properties
custom-app.enable-mocks = false
@Value("${custom-app.enable-mocks}")
private boolean enableMocks;
你也可以这样做
@Component
@PropertySource("classpath:application.properties")
public class ConfigProperties {
@Autowired
private Environment env;
public String getConfigValue(String configKey){
return env.getProperty(configKey);
}
}
然后,无论您想从哪里读取application.properties,只需将密钥传递给getConfigValue方法
@Autowired
ConfigProperties configProp;
// Read server.port from app.prop
String portNumber = configProp.getConfigValue("server.port");
Spring boot允许我们使用多种方法来提供外部化配置,您可以尝试使用application.yml或yaml文件而不是属性文件,并根据不同的环境提供不同的属性文件设置 我们可以将每个环境的属性分离到单独的spring概要文件下的单独yml文件中。然后在部署期间,您可以使用:
java -jar -Drun.profiles=SpringProfileName
指定要使用的spring配置文件。请注意,yml文件的名称应与
application-{environmentName}.yml
让它们自动被springboot接受
参考:
要从application.yml或属性文件中读取,请执行以下操作:
从属性文件或yml中读取值的最简单方法是使用spring@value注释。spring会自动将yml中的所有值加载到spring环境中,因此我们可以直接从环境中使用这些值,如:
@Component
public class MySampleBean {
@Value("${name}")
private String sampleName;
// ...
}
或者spring提供的另一种读取强类型bean的方法如下:
YML
ymca:
remote-address: 192.168.1.1
security:
username: admin
读取yml的相应POJO:
@ConfigurationProperties("ymca")
public class YmcaProperties {
private InetAddress remoteAddress;
private final Security security = new Security();
public boolean isEnabled() { ... }
public void setEnabled(boolean enabled) { ... }
public InetAddress getRemoteAddress() { ... }
public void setRemoteAddress(InetAddress remoteAddress) { ... }
public Security getSecurity() { ... }
public static class Security {
private String username;
private String password;
public String getUsername() { ... }
public void setUsername(String username) { ... }
public String getPassword() { ... }
public void setPassword(String password) { ... }
}
}
上述方法适用于yml文件
参考资料:对于我来说,以上所有内容都不能直接对我起作用。 我所做的是: 除了@Rodrigo Villalba Zayas的回答之外,我还添加了
对类实现初始化bean
并实现了该方法
@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);
}
}
获取属性值的最佳方法是使用 1。使用值注释
@Value("${property.key}")
private String propertyKeyVariable;
@Autowired
private Environment env;
public String getValue() {
return env.getProperty("property.key");
}
public void display(){
System.out.println("# Value : "+getValue);
}
@Value("${<property.name>}")
private static final <datatype> PROPERTY_NAME;
@PropertySource("classpath:application.properties")
//env is an Environment variable
env.getProperty(configKey);
2。使用环境bean
@Value("${property.key}")
private String propertyKeyVariable;
@Autowired
private Environment env;
public String getValue() {
return env.getProperty("property.key");
}
public void display(){
System.out.println("# Value : "+getValue);
}
@Value("${<property.name>}")
private static final <datatype> PROPERTY_NAME;
@PropertySource("classpath:application.properties")
//env is an Environment variable
env.getProperty(configKey);
目前,,
我知道以下三种方法:
1。@值
注释
@Value("${property.key}")
private String propertyKeyVariable;
@Autowired
private Environment env;
public String getValue() {
return env.getProperty("property.key");
}
public void display(){
System.out.println("# Value : "+getValue);
}
@Value("${<property.name>}")
private static final <datatype> PROPERTY_NAME;
@PropertySource("classpath:application.properties")
//env is an Environment variable
env.getProperty(configKey);
在加载类时,设置PropertySouce
变量(在类中)中属性源文件中的值。 这样你就可以很容易地拿到后记了环境
- 可通过系统环境变量访问
@ConfigurationProperties
注释。
- 这主要用于Spring项目中加载配置属性
- 它根据属性数据初始化实体
标识要加载的属性文件@ConfigurationProperties
基于配置文件变量创建bean @ConfigurationProperties(prefix = "user") @Configuration("UserData") class user { //Property & their getter / setter } @Autowired private UserData userData; userData.getPropertyName(); @配置属性(前缀=“用户”) @配置(“用户数据”) 类用户{ //属性及其getter/setter } @自动连线 私有用户数据用户数据; userData.getPropertyName();@Configuration
- 最好使用
@Value
注释,它会自动为您的对象私有环境en
赋值。
这将减少您的代码,并且很容易过滤您的文件。按照以下步骤操作。
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"));
1:-创建如下所示的配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Value;
@Configuration
public class YourConfiguration{
// passing the key which you set in application.properties
@Value("${userBucket.path}")
private String userBucket;
// getting the value from that key which you set in application.properties
@Bean
public String getUserBucketPath() {
return userBucket;
}
}
2:-当您有一个配置类时,然后从您需要的配置中注入变量
@Component
public class YourService {
@Autowired
private String getUserBucketPath;
// now you have a value in getUserBucketPath varibale automatically.
}
有两条路,
@Value
@Value(“#{${application yml field name}”)
公共字符串ymlField;
或
@Configuration
类,在该类中可以添加所有@value
@配置
公共类AppConfig{
@值(“#{${application yml field name}}”)
公共字符串ymlField;
}
应用程序可以从application.properties文件中读取3种类型的值
应用程序属性
cust.data.employee.name=Sachin
cust.data.employee.dept=Cricket
config.value1: 10
config.value2: 20
config.str: This is a simle str
@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() );
}
}
类文件
我也有这个问题。但有一个非常简单的解决方案。只需在构造函数中声明变量 我的例子是: 应用程序。特性:
#Session
session.timeout=15
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;
}
SessionServiceImpl类:
#Session
session.timeout=15
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;
}
您可以使用@ConfigurationProperties。访问application.properties中定义的值既简单又容易
#datasource
app.datasource.first.jdbc-url=jdbc:mysql://x.x.x.x:3306/ovtools?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
app.datasource.first.username=
app.datasource.first.password=
app.datasource.first.driver-class-name=com.mysql.cj.jdbc.Driver
server.port=8686
spring.jpa.hibernate.ddl-auto=update
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
spring.jpa.database=mysql
您可以从中使用
@Value(“${property name}”)
如果您的类被注释为
@配置
或@组件
我尝试过的另一种方法是创建一个实用程序类,用以下方式读取属性-
protected PropertiesUtility () throws IOException {
properties = new Properties();
InputStream inputStream =
getClass().getClassLoader().getResourceAsStream("application.properties");
properties.load(inputStream);
}
您可以使用静态方法获取作为参数传递的键的值。您可以使用
@value
注释从application.properties/yml文件读取值
@Value(“${application.name}”)
私有字符串applicationName;