问题
I want to access values provided in application.properties
, e.g.:
logging.level.org.springframework.web: DEBUG
logging.level.org.hibernate: ERROR
logging.file=${HOME}/application.log
userBucket.path=${HOME}/bucket
I want to access userBucket.path
in my main program in a Spring Boot application.
回答1:
You can use the @Value
annotation and access the property in whichever Spring bean you're using
@Value("${userBucket.path}")
private String userBucketPath;
The Externalized Configuration section of the Spring Boot docs, explains all the details that you might need.
回答2:
Another way is injecting Environment to your bean.
@Autowired
private Environment env;
....
public void method() {
.....
String path = env.getProperty("userBucket.path");
.....
}
回答3:
@ConfigurationProperties
can be used to map values from .properties
( .yml
also supported) to a POJO.
Consider the following Example file.
.properties
cust.data.employee.name=Sachin
cust.data.employee.dept=Cricket
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
}
Now the properties value can be accessed by autowiring employeeProperties
as follows.
@Autowired
private Employee employeeProperties;
public void method() {
String employeeName = employeeProperties.getName();
String employeeDept = employeeProperties.getDept();
}
回答4:
You can do it this way as well....
@Component
@PropertySource("classpath:application.properties")
public class ConfigProperties {
@Autowired
private Environment env;
public String getConfigValue(String configKey){
return env.getProperty(configKey);
}
}
Then wherever you want to read from application.properties, just pass the key to getConfigValue method.
@Autowired
ConfigProperties configProp;
// Read server.port from app.prop
String portNumber = configProp.getConfigValue("server.port");
回答5:
You can use the @Value
to load variables from the application.properties
if you will use this value in one place, but if you need a more centralized way to load this variables @ConfigurationProperties
is a better approach.
Additionally you can load variables and cast it automatically if you need different data types to perform your validations and business logic.
application.properties
custom-app.enable-mocks = false
@Value("${custom-app.enable-mocks}")
private boolean enableMocks;
回答6:
Currently, I know about the following three ways:
The
@Value
annotation@Value("${<property.name>}") private static final <datatype> PROPERTY_NAME;
- In my experience there are some situations when you are not
able to get the value or it is set to
null
. For instance, when you try to set it in apreConstruct()
method or aninit()
method. This happens because the value injection happens after the class is fully constructed. This is why it is better to use the 3'rd option.
- In my experience there are some situations when you are not
able to get the value or it is set to
The
@PropertySource
annotation@PropertySource("classpath:application.properties") //env is an Environment variable env.getProperty(configKey);
PropertySouce
sets values from the property source file in anEnvironment
variable (in your class) when the class is loaded. So you able to fetch easily afterword.- Accessible through System Environment variable.
The
@ConfigurationProperties
annotation.- This is mostly used in Spring projects to load configuration properties.
- It initializes an entity based on property data.
@ConfigurationProperties
identifies the property file to load.@Configuration
creates a bean based on configuration file variables.
@ConfigurationProperties(prefix = "user") @Configuration("UserData") class user { //Property & their getter / setter } @Autowired private UserData userData; userData.getPropertyName();
回答7:
Spring-boot allows us several methods to provide externalized configurations , you can try using application.yml or yaml files instead of the property file and provide different property files setup according to different environments.
We can separate out the properties for each environment into separate yml files under separate spring profiles.Then during deployment you can use :
java -jar -Drun.profiles=SpringProfileName
to specify which spring profile to use.Note that the yml files should be name like
application-{environmentName}.yml
for them to be automatically taken up by springboot.
Reference : https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-profile-specific-properties
To read from the application.yml or property file :
The easiest way to read a value from the property file or yml is to use the spring @value annotation.Spring automatically loads all values from the yml to the spring environment , so we can directly use those values from the environment like :
@Component
public class MySampleBean {
@Value("${name}")
private String sampleName;
// ...
}
Or another method that spring provides to read strongly typed beans is as follows:
YML
ymca:
remote-address: 192.168.1.1
security:
username: admin
Corresponding POJO to read the yml :
@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) { ... }
}
}
The above method works well with yml files.
Reference: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html
回答8:
For me, none of the above did directly work for me. What I did is the following:
Additionally to @Rodrigo Villalba Zayas answer up there I addedimplements InitializingBean
to the class
and implemented the method
@Override
public void afterPropertiesSet() {
String path = env.getProperty("userBucket.path");
}
So that will look like
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);
}
}
回答9:
Best ways to get property values are using.
1. Using Value annotation
@Value("${property.key}")
private String propertyKeyVariable;
2. Using Enviornment bean
@Autowired
private Environment env;
public String getValue() {
return env.getProperty("property.key");
}
public void display(){
System.out.println("# Value : "+getValue);
}
回答10:
The best thing is to use @Value
annotation it will automatically assign value to your object private Environment en
.
This will reduce your code and it will be easy to filter your files.
回答11:
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"));
来源:https://stackoverflow.com/questions/30528255/how-to-access-a-value-defined-in-the-application-properties-file-in-spring-boot