Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring 3.0.5 doesn't evaluate @Value annotation from properties

Trying to auto-wire properties to a bean in Spring 3.0.5.RELEASE, I'm using:

  • config.properties:

    username=myusername 
  • main-components.xml:

    <context:property-placeholder location="classpath:config.properties" /> 
  • MyClass:

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

As a result, username gets set to literally "${username}", so the expression doesn't get parsed. My other auto-wired dependencies on this class get set, and Spring doesn't throw any exception. I also tried to add @Autowired but it didn't help.

If I parse properties to a separate bean and then use @Autowired + @Qualifier, it works:

<bean id="username" class="java.lang.String">     <constructor-arg value="${username}"/> </bean> 

Any ideas how to use just @Value? Maybe I need to include some Spring dependency that I haven't? Thank you

like image 676
Alex Yarmula Avatar asked Mar 11 '11 16:03

Alex Yarmula


People also ask

What is the use of @value annotation in spring?

One of the most important annotations in spring is @Value annotation which 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. It also supports Spring Expression Language (SpEL).

Is @value reading from property file in Spring Boot?

The Spring @Value is not reading from property file, but instead it's taking the value literally @Component public class AppConfig { @Value ("$ {key.value1}") private String value; public String getValue () { return value; } }

How do I inject a map property using the @value annotation?

We can also use the @Value annotation to inject a Map property. First, we'll need to define the property in the {key: ‘value' } form in our properties file: Note that the values in the Map must be in single quotes. Now we can inject this value from the property file as a Map:

How to inject literal values into configuration variables in spring?

It is generally used for injecting values into configuration variables, which we will show and explain in the following example. Step 1: First, let’s create a simple Spring Application and inject the literal values by setter injection. So, create a simple class Student having three attributes rollNo, name, and age.


1 Answers

Found what the issue was. Copy/paste from comments:

Are you sure you have <context:property-placeholder> in the same application context as your MyClass bean (not in the parent context)? – axtavt

You're right. I moved <context:property-placeholder> from the context defined by the ContextLoaderListener to the servlet context. Now my values get parsed. Thanks a lot! - alex

like image 154
Alex Yarmula Avatar answered Sep 20 '22 23:09

Alex Yarmula