Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I inject a property value into an annotation configured spring mvc 3.0 controller

Tags:

java

spring

First: I'm using Spring 3.0

I have a problem when configuring my controller class. The controller uses a web service which I want to define the endpoint address using a .properties file.

@Controller
public class SupportController {

    @Value("#{url.webservice}") 
    private String wsEndpoint;

    ...

In my application context xml-file, I've defined this:

<context:property-placeholder location="/WEB-INF/*.properties" />

I've been reading the documentation, trying different approaches (like adding prefix systemProperties.),but I keep getting an error message telling me that it doesn't exist.

Field or property 'url' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext'


Ok. I've figured it out.

Now, in the controller:

@Value("#{settings['url.webservice']")

Then in the context configuration I have this "helper bean":

<util:properties id="settings" 
location="/WEB-INF/supportweb.properties"></util:properties>
like image 576
l3dx Avatar asked Jan 13 '10 09:01

l3dx


People also ask

How property values can be injected in Spring Boot?

Property values can be injected directly into your beans using the @Value annotation, accessed via Spring's Environment abstraction or bound to structured objects via @ConfigurationProperties . Spring Boot uses a very particular PropertySource order that is designed to allow sensible overriding of values.

How do you inject property value into a class not managed by Spring?

Load Configuration With Class Loader Instead of using third party implementations that support automatic application configuration loading, e.g. that implemented in Spring, we can use Java ClassLoader to do the same. We're going to create a container object that will hold Properties defined in resourceFileName.

Which annotation can be used to inject a default value?

Spring @Value annotation is used to assign default values to variables and method arguments. We can read spring environment variables as well as system variables using @Value annotation. Spring @Value annotation also supports SpEL. Let's look at some of the examples of using @Value annotation.


2 Answers

I have this configuration and it works fine:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
       <list>
         <value>classpath:application.properties</value>
      </list>
    </property>
</bean>

and I iniejct the property in this way

@Value("${root.log.level}") 
private String prop;

the field is correctly initialized to "DEBUG" value.

like image 192
Enrico Avatar answered Sep 28 '22 12:09

Enrico


This should work, too:

@Value("${url.webservice}") 
private String wsEndpoint;
like image 34
GeertPt Avatar answered Sep 28 '22 12:09

GeertPt