Tim Long
Tim Long

Reputation: 2149

Spring Bean definition with value from application.yml

I want to define a Bean which should be managed by Spring and having its properties being injected from application.yml.

application.yml //
client:
   port: 80
   address: "xyz.net"
   timeout: 100



Client.java // this class is external, we cannot change it
public class Client {
    private final int port;
    private final String address;
    public void setPortAddress(String address, int port) //
    ...
}

I did try using @Configuration but it's not working. The error is address is not set, while trying to access the client instance.

Service.java //

@Configuration
@ConfigurationProperties(prefix="client")
@ComponentScan(basePackageClasses=Service.class)
public class Config {
   int port;
   String address;

   @Bean
   Client getClient(){
      Client client = new Client();
      client.setPortAddress(address, port);
      return client;
   }
} 

Any help is very thankful.

Upvotes: 0

Views: 2751

Answers (1)

ivospijker
ivospijker

Reputation: 732

It looks like you haven't mapped the application.yml file to a Spring object yet.

One way to achieve this, is using @ConfigurationProperties. You can learn more about them here: https://www.baeldung.com/configuration-properties-in-spring-boot

For your example, I would propose the following:

New class to add:

@Configuration
@ConfigurationProperties(prefix = "client")
public class ClientProperties {
    
    private int port;
    private String address;

    // standard getters and setters
}

Autowire this as a parameter of your getClient() method

@Configuration
public class Config {

   @Bean
   Client getClient(ClientProperties properties){
      Client client = new Client();
      client.setPortAddress(properties.getAddress(), properties.getPort());
      return client;
   }
} 

Upvotes: 1

Related Questions