riorio
riorio

Reputation: 6826

Spring Boot and properties data from Yml file

My Spring boot app is failing to create a bean with the properties object from the application.yml.

Here is what I did:

application.yml:

statsd:
   host: 10.0.5.23
   port: 8125

I created a StatsdProperties @Componentclass to hold the above data:

@Component
@ConfigurationProperties(prefix="statsd")
public class StatsdProperties {
   private String host;
   private int port;

   .... getters & setters
}

And I created another @Component class that should use the above properties:

 @Component
 public class MyClass{

   @Autowired
   private StatsdProperties statsdProperties;


   public MyClass(){
      statsdProperties.getPort()  <---  statsdProperties is null here
   }

And statsdProperties is null in the MyClass

What am I doing wrong?

Upvotes: 0

Views: 578

Answers (2)

Always Learning
Always Learning

Reputation: 2743

Update your configuration file to this:

@Configuration
@EnableConfigurationProperties()
@ConfigurationProperties(prefix = "statsd")
public class StatsdProperties  {
  private String host;
  private int port;

  .... getters & setters
}

Upvotes: 1

Mạnh Quyết Nguyễn
Mạnh Quyết Nguyễn

Reputation: 18235

You need to enable configuration in your MyClass:

 @Component
 @EnableConfigurationProperties(StatsdProperties.class)
 public class MyClass

Upvotes: 0

Related Questions