Home  >  Forum  >  Spring
Post New Query

Spring @ConfigurationProperties not working



Asked on June 09, 2019
I want to use Spring Boot @ConfigurationProperties in my application. But its is not working. Find my code.

1.

@Configuration
@PropertySource("classpath:user.properties")
public class AppConfig {
@Bean
public User getUser() {
User user = new User();
return user;
}
}

2.

@ConfigurationProperties
public class User {
String name;
String age;
}

3.
//user.properties

name=John
age=30

4.

@SpringBootApplication
@EnableConfigurationProperties
public class MySpringBootApp {
public static void main(String[] args) {
final ApplicationContext ctx = SpringApplication.run(MySpringBootApp.class, args);
final User user = ctx.getBean(User.class);
System.out.println(user.name);
System.out.println(user.age);
}
}

5.
//Output
null
null


How to fix it?




Replied on June 09, 2019
You are missing setters and getters in User class. Create setters and getters.

@ConfigurationProperties
public class User {
    String name;
    String age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAge() {
        return age;
    }
    public void setAge(String age) {
        this.age = age;
    }
}

Then try.



Replied on June 09, 2019
Great. It is working.

Write Answer








©2019 concretepage.com | Privacy Policy | Contact Us