Ask Your Question
4

How can a custom class be configured with a Spring @Value property?

asked 2023-05-25 11:48:50 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-05-25 12:13:02 +0000

woof gravatar image

To configure a custom class with a Spring @Value property, you need to follow the below steps:

  1. Create a custom class with instance variables for the values you want to set via @Value annotation:
public class CustomClass {
    private String endpointUrl;
    private String apiKey;

    // constructor and getters/setters
}
  1. In your Spring configuration class, create an instance of the custom class and annotate it with @Component:
@Component
public class MyConfig {

    @Value("${api.endpoint}")
    private String endpointUrl;

    @Value("${api.key}")
    private String apiKey;

    @Bean
    public CustomClass customClass() {
        return new CustomClass(endpointUrl, apiKey);
    }

}
  1. Use the created bean in your application:
@Autowired
private CustomClass customClass;

// use customClass instance variables as required

In the example above, we used @Value to load the values for endpointUrl and apiKey from properties files. You can also use other sources such as system properties or environment variables.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-25 11:48:50 +0000

Seen: 1 times

Last updated: May 25 '23