456

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.

Nat Ritmeyer
  • 5,546
  • 8
  • 42
  • 56
Qasim
  • 7,702
  • 7
  • 34
  • 49

32 Answers32

671

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.

johnnyRose
  • 6,834
  • 17
  • 41
  • 61
Master Slave
  • 26,268
  • 4
  • 56
  • 55
  • 17
    as en alternative one can get those also from spring `Environment` or via `@ConfigurationProperties` – sodik May 29 '15 at 14:35
  • 5
    To add on top of @sodik's answer, this is an example that shows how to get the [Environment](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/env/Environment.html) http://stackoverflow.com/questions/28392231/how-to-determine-programmatically-the-current-active-profile-using-spring-boot – cristi May 06 '16 at 17:59
  • What if you need to access over 10 values, Would you have to keep repeating your example 10times? – Jodi Dec 06 '16 at 20:06
  • one approach would be to do so, but its cumbersome. There are alternative approaches based on `@Configuration` classes, problem is well analyzed in the following [blog post](https://www.petrikainulainen.net/programming/spring-framework/spring-from-the-trenches-injecting-property-values-into-configuration-beans/) – Master Slave Dec 06 '16 at 20:33
  • Adding this answer you can add some value if the property configuration is not found by default some value adding: @Value("${userBucket.path:~/bucket}") or empty @Value("${userBucket.path:}") – Jonathan JOhx Nov 01 '18 at 19:27
  • 12
    Note, this only works on a `@Component` (or any of its derivatives, i.e. `@Repository`, etc.) – Janac Meena Oct 10 '19 at 15:20
  • I use this on Controller and it's work – Faisal Mar 29 '22 at 18:07
311

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");
    .....
}
JoshDM
  • 4,837
  • 7
  • 43
  • 72
Rodrigo Villalba Zayas
  • 4,836
  • 2
  • 21
  • 36
52

@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();

}
Jobin
  • 5,160
  • 5
  • 33
  • 52
  • 2
    i used this way and got null return, i put my properties file in src/test/resources and properties java class (in which the properties value being saved) in src/main/package/properties. what i been missing? thanks – Ahmad Leo Yudanto Nov 16 '19 at 13:16
  • you have to save the files to `src/main/resources` if you are not testing your code from a Spring test. – Jobin Nov 17 '19 at 08:29
  • Same as @AhmadLeoYudanto and there is nothing I can do that change that – Dimitri Kopriwa Apr 02 '20 at 09:25
27

Currently, I know about the following three ways:

1. 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 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 3'rd 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.
  • Accessible through System Environment variable.

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();
Community
  • 1
  • 1
Dhwanil Patel
  • 1,905
  • 1
  • 14
  • 23
  • What if the default location is overridden with `spring.config.location`? Does #2 still work? – bmauter Apr 06 '20 at 14:18
  • In such case, priority comes into the place. As per i know when you set spring.config.location using command line it have high priority so it override existing one. – Dhwanil Patel Apr 06 '20 at 17:10
  • 1
    Many thanks for this >> "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 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 3'rd option."< – Bhushan Karmarkar Jun 16 '21 at 13:00
15

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"); 
lucifer
  • 375
  • 3
  • 13
12

follow these steps. 1:- 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;
    }
}

2:- 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 getUserBucketPath varibale automatically.
}
Fazle Subhan
  • 171
  • 1
  • 5
9

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 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;
Jorge Tovar
  • 417
  • 4
  • 13
  • The casting is very nice. What additional is necessary as I get "Annotations not allowed here" no matter where I put it. I am missing something. Do I need a some other per-configuration to use this annotation anywhere? – cp. Jul 26 '21 at 17:00
8

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.

Arghya Sadhu
  • 35,183
  • 9
  • 62
  • 80
Shreyanshi
  • 96
  • 1
  • 4
5

@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

  1. String value from the annotation to the field
    @Value("string value identifire in property file")
    private String stringValue;
  1. 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;
  1. We can also use the @Value annotation to inject a List property.
   @Value("#{'${listOfValues}'.split(',')}")
   private List<String> valuesList;
Tenusha Guruge
  • 1,891
  • 2
  • 14
  • 37
5

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 below example,

application.properties

myapp.nationality: INDIAN
myapp.gender: Male

Below is corresponding reader class.

@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "myapp") 
class AppConfigReader{
    private String nationality;
    private String gender

    //getter & 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 config reader
    String nationality = appConfigReader.getNationality() ; 
    String gender = appConfigReader.getGender(); 
}
Akash Verma
  • 366
  • 1
  • 5
  • 13
5

Maybe it can help others: you should inject @Autowired private Environment env; from import org.springframework.core.env.Environment;

and then use it this way : env.getProperty("yourPropertyNameInApplication.properties")

ZahraAsgharzade
  • 185
  • 2
  • 10
4

An application can read 3 types of value from the application.properties file.

application.properties


     my.name=kelly

my.dbConnection ={connection_srting:'http://localhost:...',username:'benz',password:'pwd'}

class file

@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 default value

        @Value("${your_name : default value}")
         private String msg; 
NafazBenzema
  • 1,185
  • 1
  • 12
  • 30
3

You can use the @Value annotation for reading values from an application.properties/yml file.

@Value("${application.name}")
private String applicationName;
Birju Vachhani
  • 5,602
  • 4
  • 19
  • 42
Manju D
  • 91
  • 2
2

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

Ananthapadmanabhan
  • 4,855
  • 5
  • 19
  • 35
2

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);
}
Naresh Bhadke
  • 243
  • 5
  • 15
2
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"));
sai
  • 91
  • 1
  • 3
  • Where is setUrl defined? How come I get a compiler error. Actually I'm more interested in setPassword if possible. Thanks. – Louis Aug 27 '21 at 14:23
2

There are 2 ways to access value from application.properties file

  1. Using @Value annotation
    @Value("${property-name}")
    private data_type var_name;
  1. Using instance of 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 instance of environment using constructor injection or creating a bean yourself

2

You have multiple method to read values from properties file .

  1. Using @Value Annotation

    @Service public class EmailService {

        @Value("${email.username}")
        private String username;
    
     }
    
  2. Using @ConfigurationProperties annotation

       @Component
       @ConfigurationProperties("email")
       public class EmailConfig {
    
            private String   username;
    
             public String getUsername() {
                      return username;
              }
    
       }
    

References : How to read Properties file in Spring Boot

1

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.

Shafin Mahmud
  • 3,407
  • 1
  • 21
  • 33
Amit Mishra
  • 463
  • 5
  • 14
1

There are two way,

  1. you can directly use @Value in you class
    @Value("#{'${application yml field name}'}")
    public String ymlField;

OR

  1. 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;
}
Rishabh Agarwal
  • 1,721
  • 1
  • 15
  • 24
1

Tried Class PropertiesLoaderUtils ?

This approach uses no annotation of Spring boot. A traditional Class way.

example:

Resource resource = new ClassPathResource("/application.properties");
    Properties props = PropertiesLoaderUtils.loadProperties(resource);
    String url_server=props.getProperty("server_url");

Use getProperty() method to pass the key and access the value in the properties file.

1

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"));
    }
} 
David
  • 126
  • 1
  • 5
1

You can access the application.properties file values by using:

@Value("${key_of_declared_value}")
Suraj Rao
  • 28,850
  • 10
  • 94
  • 99
1

There are 3 ways to read the application.properties,

using @Value, EnvironmentInterface and @ConfigurationProperties..

@Value(${userBucket.path})
private String value;

2nd way:

@Autowired
private Environment environment;

String s = environment.getProperty("userBucket.path");

3rd way:

@ConfigurationProperties("userbucket")
public class config {

private String path;
//getters setters

}

Can be read with getters and setters..

Reference - here

JavaLearner
  • 242
  • 1
  • 10
0

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 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);
    }
}
Airn5475
  • 2,264
  • 27
  • 46
Rapalagui
  • 69
  • 2
  • 9
0

I had this problem too. But there is very simple solution. Just declare your variable in 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;
}
Seldo97
  • 513
  • 1
  • 4
  • 13
0

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);
    }
BRAIEK AYEMN
  • 89
  • 1
  • 5
0

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() );
    }
}
LazyAnalyst
  • 386
  • 1
  • 14
0

@Value("${userBucket.path}") private String userBucketPath;

  • 3
    Please, add an explanation. See [how to answer](https://stackoverflow.com/help/how-to-answer). – Syscall Apr 13 '21 at 08:43
0

You can use the @Value annotation and access the property in spring bean

@Value("${userBucket.path}")
private String userBucketPath;
0

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:

  1. Autowire the environment variable to your class where you need to access this property:

@Autowired private Environment environment

  1. Use the environment variable to get the property value in the line you need it using:

environment.getProperty("userBucket.path");

Hope this answers your question!

0

To read application.properties or application.yml attributes follow the following steps:

  1. Add your attributes in application.properties or application.yaml
  2. Create config class and add your attributes
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()

}
Talat El Beick
  • 265
  • 5
  • 8