Monday, February 1, 2021

@Value Properties in Spring - How to use and configure ?

First We need to tell Spring where are the property files located
We can use xml-based or annotation based approach

Xml-Based Approach -  <context:property-placeholder>
 
1
2
3
<context:property-placeholder location="classpath:foo.properties"/>
<context:property-placeholder location="file:bar.properties"/>
<context:property-placeholder location="${databaseProperties}.properties"/>

"classpath:foo.properties" ---> Searches in Classpath
"file:bar.properties"      ---> Searches in filepath
This is Spring format having "file:" as prefix

If you want to make Filepath Dynamic - We can save the path and pass it to JVM Arg Value, For Example
 
-DdatabaseProperties="file:C:/Users/Karan/Desktop/ExternalConfig/database"

We can use these properties by using
@Value + @Component /@Configuration - which can make class Bean Managed
-------------------------------------------------------------------------------------
https://www.baeldung.com/spring-value-annotation
https://www.baeldung.com/properties-with-spring
https://www.baeldung.com/spring-autowire
-------------------------------------------------------------------------------------
Using Annotation
@PropertySource("classpath:foo.properties")
@PropertySource("classpath:bar.properties")
public class PropertiesWithJavaConfig {
    //...
}

Default values can be provided for properties that might not be defined. Here, the value some default will be injected:

@Value("${unknown.param:some default}")
private String someDefault;

When we use the @Value annotation, we're not limited to a field injection. We can also use it together with constructor injection.

Let's see this in practice:

@Component
@PropertySource("classpath:values.properties")
public class PriorityProvider {

    private String priority;

    @Autowired
    public PriorityProvider(@Value("${priority:normal}") String priority) {
        this.priority = priority;
    }

    // standard getter
}

No comments:

Post a Comment

Azure - Pipeline - Add Approver for Stage

https://learn.microsoft.com/en-us/azure/devops/pipelines/process/approvals?view=azure-devops&tabs=check-pass