Home > Software design >  Spring Boot: Using values from application.properties in named properties of annotations on class he
Spring Boot: Using values from application.properties in named properties of annotations on class he

Time:10-01

It is known that some annotations have named properties, such as:

@MyAnnotation(name="myName", url="http://www.example.com")

Now if I were to use this annotation in MyClass like this:

@MyAnnotation(name="myName", url="http://www.example.com")
public class MyClass {
   ...
}

but move the values "myName" and "http://www.example.com" into application.properties like this:

services.name=myName
services.url=http://www.example.com

then how can I access these properties from MyClass?

CodePudding user response:

You can achieve binding using @ConfigurationProperties annotation.

@Configuration
@ConfigurationProperties(prefix = "services")
public class MyClass {
   private String name;
   private String url;
}

We use @Configuration so that Spring creates a Spring bean in the application context.

@ConfigurationProperties works best with hierarchical properties that all have the same prefix; therefore, we add a prefix of mail.

The Spring framework uses standard Java bean setters, so we must declare setters for each of the properties.

Note: If we don't use @Configuration in the POJO, then we need to add @EnableConfigurationProperties(ConfigProperties.class) in the main Spring application class to bind the properties into the POJO:

@SpringBootApplication
@EnableConfigurationProperties(MyClass.class)
public class EnableConfigurationDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(EnableConfigurationDemoApplication.class, args);
    }
}

Spring will automatically bind any property defined in our property file that has the prefix services and the same name as one of the fields in the ConfigProperties class.

References :

https://www.baeldung.com/configuration-properties-in-spring-boot

CodePudding user response:

You can simply use @Value annotation. For that your class must managed by Spring. In other words your class must be a Spring Bean.

Something like this,

@Service
public class MyClass {
   @Value("${services.name}")
   private String name;

   @Value("${services.url}")
   private String url;
}

Note: For more info here

You can also create custom configuration property class. Something like this,

@Configuration
@ConfigurationProperties("services")
public class MyClass {
   private String name;
   private String url;
}

Note: For more info here

  • Related