Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a property value from an ApplicationContext object? (not using an annotation)

If I have:

@Autowired private ApplicationContext ctx; 

I can get beans and resources by using one of the the getBean methods. However, I can't figure out how to get property values.

Obviously, I can create a new bean which has an @Value property like:

private @Value("${someProp}") String somePropValue; 

What method do I call on the ApplicationContext object to get that value without autowiring a bean?

I usually use the @Value, but there is a situation where the SPeL expression needs to be dynamic, so I can't just use an annotation.

like image 878
HappyEngineer Avatar asked May 30 '12 19:05

HappyEngineer


People also ask

How do I get property properties from Spring boot?

Using the Environment Object Another method to access values defined in Spring Boot is by autowiring the Environment object and calling the getProperty() method to access the value of a property file.

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.

How do I get an ApplicationContext object?

To get a reference to the ApplicationContext in a Spring application, it can easily be achieved by implementing the ApplicationContextAware interface. Spring will automatically detect this interface and inject a reference to the ApplicationContext: view rawMyBeanImpl. java hosted by GitHub.


1 Answers

In the case where SPeL expression needs to be dynamic, get the property value manually:

somePropValue = ctx.getEnvironment().getProperty("someProp"); 
like image 67
Italo Borssatto Avatar answered Oct 13 '22 07:10

Italo Borssatto