Spring 4: @PropertySource and Environment example

Today we will see how to load and read from property file in Spring 4 using @PropertySource annotation and Environment class.


Let’s say we have the User class


public class User {
    private String name;
    private int age;
    private String country;

    public User(String name, int age, String country) {
        this.name = name;
        this.age = age;
        this.country = country;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String getCountry() {
        return country;
    }
}

Our goal is to create user object and fill up the user details with the properties specified in user.properties
we have the following property file:

name=Tom
age=30
country=USA

In order to load the property file we will add @PropertySource annotation to our spring config class. And later we will get the properties using Environment class


@Configuration
@ComponentScan("com.blog.spring.domain")
@PropertySource("classpath:user.properties")
public class ConfigEnv {

    @Autowired
    Environment env;

    @Bean
    public User getUser() {
        String name = env.getProperty("name");
        //we can specify the property type
        int age = env.getProperty("age", Integer.class);
        String country = env.getProperty("country");
        return new User(name, age, country);
    }
}

Let’s run and see the output:

public class UserApp {
    public static void main(String[] args) {
        ApplicationContext context =
                new AnnotationConfigApplicationContext(ConfigEnv.class);

        User user = context.getBean(User.class);
        System.out.println("name --> "+user.getName());
        System.out.println("age --> "+user.getAge());
        System.out.println("country --> "+user.getCountry());

    }
}
[addToAppearHere]

Output:

name --> Tom
age --> 30
country --> USA

Environment class provides different ways for getting properties. As we saw we can specify the property type:

int age = env.getProperty("age", Integer.class);

We can specify also the default value in case property is not there

int age = env.getProperty("age", 25);
int age = env.getProperty("age", Integer.class, 25);

If the property is required we can do:

int age = env.getRequiredProperty("age", Integer.class);