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
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).
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; } }
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:
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With