Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Spring: How to use `@Value` annotation to inject an `Environment` property?

Using a construct such as

@Component public class SomeClass {      @Inject     private Environment env;      private String key;       @PostConstruct     private void init() {          key = env.getProperty("SOME_KEY_PROPERTY");      }      .... } 

it is possible to assign some field with some property.

Is there a shorter, more concise form to do this?

like image 787
Abdull Avatar asked Jan 31 '13 01:01

Abdull


People also ask

How do you inject annotations in Spring properties?

Spring get value from system property. You can set the system property on the Java command line using the -Dpropertyname=value syntax or at runtime using System. setProperty function. To inject the value from the system property, annotate your field using the @Value annotation with SpEL expression as below.

What annotation can inject a property into Java code?

Using @Value With Maps We can also use the @Value annotation to inject a Map property.

How property values can be injected directly into your beans in Spring boot?

Most people know that you can use @Autowired to tell Spring to inject one object into another when it loads your application context. A lesser known nugget of information is that you can also use the @Value annotation to inject values from a property file into a bean's attributes.

Which annotation is used to inject property values into beans?

The Javadoc of the @Value annotation.


2 Answers

@Component public class SomeClass {      @Value("#{environment.SOME_KEY_PROPERTY}")     private String key;      .... } 
like image 199
Abdull Avatar answered Oct 20 '22 11:10

Abdull


You should be able to do this(assuming that you have a PropertySourcesPlaceHolderConfigurer registered)

@Value("${SOME_KEY_PROPERTY}") private String key; 
like image 41
Biju Kunjummen Avatar answered Oct 20 '22 09:10

Biju Kunjummen