Reputation: 9658
How can I access values provided in application.properties
, like
logging.level.org.springframework.web: DEBUG
logging.level.org.hibernate: ERROR
logging.file=${HOME}/application.log
userBucket.path=${HOME}/bucket
For instance, I want to access userBucket.path
in my main program in a Spring Boot application.
Upvotes: 587
Views: 1117010
Reputation: 627
There are actually three ways to read the application.properties
file,
TLDR: use @ConfigurationProperties
Environment
:@Autowired
Environment environment
environment.getProperty({propertyName})
@Value
:@Value("${property}")
Be aware that @Value
will throw an exception if the property key (i.e. property
in example above) is not in the properties file.
@ConfigurationProperties
:@ConfigurationProperties("userBucket")
public class PropertiesTest {
private String path;
//getters and setters
}
For a detailed example, see Reading application.properties.
Upvotes: 3
Reputation: 28569
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.
Upvotes: 844
Reputation: 322
There are 3 ways to read the application.properties
:
1st way:
Using @Value
, EnvironmentInterface
and @ConfigurationProperties
:
@Value("${userBucket.path}")
private String value;
2nd way:
@Autowired
private Environment environment; // org.springframework.core.env.Environment;
String s = environment.getProperty("userBucket.path");
3rd way:
@ConfigurationProperties("userbucket")
public class Config {
private String path;
// getters and setters
}
Can be read with getters and setters..
Reference - here
Upvotes: 9
Reputation: 31
You can use the @Value annotation and access the property in a Spring bean:
@Value("${userBucket.path}")
private String userBucketPath;
Upvotes: 1
Reputation: 309
You should inject @Autowired private Environment env;
from import org.springframework.core.env.Environment;
And then use it this way:
env.getProperty("yourPropertyNameInApplication.properties")
Upvotes: 7
Reputation: 87
You can use @ConfigurationProperties. It's simple and easy to access a value defined in 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
@Slf4j
@Configuration
public class DataSourceConfig {
@Bean(name = "tracenvDb")
@Primary
@ConfigurationProperties(prefix = "app.datasource.first")
public DataSource mysqlDataSourceanomalie() {
return DataSourceBuilder.create().build();
}
@Bean(name = "JdbcTemplateenv")
public JdbcTemplate jdbcTemplateanomalie(@Qualifier("tracenvDb") DataSource datasourcetracenv) {
return new JdbcTemplate(datasourcetracenv);
}
Upvotes: 0
Reputation: 847
To pick the values from property file, we can have a Config reader class, something like ApplicationConfigReader.java. Then define all the variables against properties. Refer to the below example,
application.properties
myapp.nationality: INDIAN
myapp.gender: Male
Below is the corresponding reader class.
@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "myapp")
class AppConfigReader{
private String nationality;
private String gender
// Getter and setter
}
Now we can auto-wire the reader class wherever we want to access property values.
E.g.,
@Service
class ServiceImpl{
@Autowired
private AppConfigReader appConfigReader;
//...
// Fetching values from the configuration reader
String nationality = appConfigReader.getNationality() ;
String gender = appConfigReader.getGender();
}
Upvotes: 7
Reputation: 99
Try class PropertiesLoaderUtils. This approach doesn’t use any annotation of Spring Boot. It is a traditional class way.
Example:
Resource resource = new ClassPathResource("/application.properties");
Properties props = PropertiesLoaderUtils.loadProperties(resource);
String url_server=props.getProperty("server_url");
Use the getProperty() method to pass the key and access the value in the properties file.
Upvotes: 2
Reputation: 81
There are two ways to access the value from the application.properties file:
Using the @Value annotation
@Value("${property-name}")
private data_type var_name;
Using an instance of the Environment class
@Autowired
private Environment environment;
// Access this way in the method where it's required
data_type var_name = environment.getProperty("property-name");
You can also inject an instance of the environment using constructor injection or creating a bean yourself.
Upvotes: 3
Reputation: 719
I had this problem too. But there is a very simple solution. Just declare your variable in the constructor.
My example:
application.propperties:
#Session
session.timeout=15
SessionServiceImpl class:
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;
}
Upvotes: 0
Reputation: 1698
An application can read three types of values from the application.properties file.
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;
If you don't have a property in application.properties then you can use the default value:
@Value("${your_name: default value}")
private String msg;
Upvotes: 6
Reputation: 2652
There are two ways,
you can directly use @Value
in your class
@Value("#{'${application yml field name}'}")
public String ymlField;
Or
To make it clean you can clean @Configuration
class where you can add all your @value
@Configuration
public class AppConfig {
@Value("#{'${application yml field name}'}")
public String ymlField;
}
Upvotes: 2
Reputation: 261
Follow these steps.
Create your configuration class like below. You can see:
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;
}
}
When you have a configuration class then inject in the variable from a configuration where you need.
@Component
public class YourService {
@Autowired
private String getUserBucketPath;
// Now you have a value in the getUserBucketPath
// variable automatically.
}
Upvotes: 15
Reputation: 6216
Spring Boot allows us several methods to provide externalized configurations. You can try using file 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 YAML 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 YAML files should be named like
application-{environmentName}.yml
for them to be automatically taken up by Spring Boot.
Reference: 2. Externalized Configuration
To read from the application.yml or property file:
The easiest way to read a value from the property file or YAML is to use the Spring @value annotation. Spring automatically loads all values from the YAML file 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 YAML content:
@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 YAML files.
Reference: 2. Externalized Configuration
Upvotes: 2
Reputation: 139
Injecting a property with the @Value annotation is straightforward:
@Value("${jdbc.url}")
private String jdbcUrl;
We can obtain the value of a property using the Environment API
@Autowired
private Environment env;
...
dataSource.setUrl(env.getProperty("jdbc.url"));
Upvotes: 4
Reputation: 510
The best thing is to use the @Value
annotation. It will automatically assign a value to your object private Environment en
.
This will reduce your code, and it will be easy to filter your files.
Upvotes: 1
Reputation: 2573
Currently, I know about the following three ways:
1. The @Value
annotation
@Value("${<property.name>}")
private static final <datatype> PROPERTY_NAME;
null
.
For instance, when you try to set it in a preConstruct()
method or an init()
method. This happens because the value injection happens after the class is fully constructed. This is why it is better to use the third option.2. The @PropertySource
annotation
@PropertySource("classpath:application.properties")
// 'env' is an Environment variable
env.getProperty(configKey);
PropertySouce
sets values from the property source file in an Environment
variable (in your class) when the class is loaded.
So you able to fetch easily afterword.3. 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();
Upvotes: 45
Reputation: 423
The best ways to get property values are using:
1. Using Value annotation
@Value("${property.key}")
private String propertyKeyVariable;
2. Using the Environment bean
@Autowired
private Environment env;
public String getValue() {
return env.getProperty("property.key");
}
public void display() {
System.out.println("# Value : " + getValue);
}
Upvotes: 2
Reputation: 89
For me, none of the above did directly work for me. I did the following:
In addition to Rodrigo Villalba Zayas' answer, I added implements 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);
}
}
Upvotes: 0
Reputation: 1879
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 these variables @ConfigurationProperties
is a better approach.
Additionally, you can load variables and cast them 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;
Upvotes: 12
Reputation: 541
To read application.properties
or application.yml
attributes follow the following steps:
application.jwt.secretKey=value
application.jwt.tokenPrefix=value
application.jwt.tokenExpiresAfterDays=value ## 14
application:
jwt:
secret-key: value
token-prefix: value
token-expires-after-days: value ## 14
@Configuration("jwtProperties") // you can leave it empty
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "application.jwt") // prefix is required
public class JwtConfig {
private String secretKey;
private String tokenPrefix;
private int tokenExpiresAfterDays;
// getters and setters
}
NOTE: in .yaml
file you have to use kabab-case
Now to use the config class just instantiate it, you can do this manualy or with dependency injection.
public class Target {
private final JwtConfig jwtConfig;
@Autowired
public Target(JwtConfig jwtConfig) {
this.jwtConfig = jwtConfig;
}
// jwtConfig.getSecretKey()
}
Upvotes: 0
Reputation: 161
You can access the application.properties file values by using:
@Value("${key_of_declared_value}")
Upvotes: 2
Reputation: 656
Another way to find a key/value in the configuration.
...
import org.springframework.core.env.ConfigurableEnvironment;
...
@SpringBootApplication
public class MyApplication {
@Autowired
private ConfigurableEnvironment myEnv;
...
@EventListener(ApplicationReadyEvent.class)
public void doSomethingAfterStartup()
throws Exception {
LOG.info("myEnv (userBucket.path): " + myEnv.getProperty("userBucket.path"));
}
}
Upvotes: 2
Reputation: 19
The easiest way would be to use the @Value annotation provided by Spring Boot. You need to define a variable at class level. For example:
@Value("${userBucket.path}") private String userBucketPath
There is another way you can do this via the Environment Class. For example:
@Autowired private Environment environment
environment.getProperty("userBucket.path");
Hope this answers your question!
Upvotes: 0
Reputation: 486
application.yml or application.properties
config.value1: 10
config.value2: 20
config.str: This is a simle str
MyConfig class
@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.
}
Any class that wants to access config values
@Import(MyConfig.class)
class MyClass {
private MyConfig myConfig;
@Autowired
public MyClass(MyConfig myConfig) {
this.myConfig = myConfig;
System.out.println( myConfig.getValue1() );
}
}
Upvotes: 0
Reputation: 300
@Value Spring annotation is used for injecting values into fields in Spring-manged beans, and it can be applied to the field or constructor/method parameter level.
Examples
@Value("string value identifire in property file")
private String stringValue;
We can also use the @Value annotation to inject a Map property.
First, we'll need to define the property in the {key: ‘value' }
form in our properties file:
valuesMap={key1: '1', key2: '2', key3: '3'}
Not that the values in the Map must be in single quotes.
Now inject this value from the property file as a Map:
@Value("#{${valuesMap}}")
private Map<String, Integer> valuesMap;
To get the value of a specific key
@Value("#{${valuesMap}.key1}")
private Integer valuesMapKey1;
@Value("#{'${listOfValues}'.split(',')}")
private List<String> valuesList;
Upvotes: 6
Reputation: 121
You can use the @Value
annotation for reading values from an application.properties/yml file.
@Value("${application.name}")
private String applicationName;
Upvotes: 3
Reputation: 146
You can use @Value("${property-name}")
from the
application.properties if your class is annotated with
@Configuration
or @Component
.
There's one more way I tried out was making a Utility class to read properties in the following way -
protected PropertiesUtility () throws IOException {
properties = new Properties();
InputStream inputStream =
getClass().getClassLoader().getResourceAsStream("application.properties");
properties.load(inputStream);
}
You can make use of static method to get the value of the key passed as the parameter.
Upvotes: 12
Reputation: 5636
Another way is injecting org.springframework.core.env.Environment
to your bean.
@Autowired
private Environment env;
....
public void method() {
.....
String path = env.getProperty("userBucket.path");
.....
}
Upvotes: 370
Reputation: 5871
@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();
}
Upvotes: 81