user9945564
user9945564

Reputation:

Spring @Value is always null

I'm using spring in my app and I have a .properties file which has some values defined.

In a java class there is a String value:

@Value("${test}")
public String value;

The point is that if I inject this value in beans definition:

<bean id="customClass" class="package.customClass.CustomClassImpl">
    <property name="value" value="${test}"></property>
</bean>

It works fine, but if I use @Value, there is always a null... Why is that happening?

And no, I'm not doing any "new" no instantiate "customClass", I get it with context.getBean("customClass).

EDIT: I have configured a property placeholder in the context:

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

Thanks in advance.

Upvotes: 5

Views: 20207

Answers (4)

AlYosha
AlYosha

Reputation: 227

If you are creating spring boot application and your goal is to provide configuration parameter(s) via (application).properties there is a way to do it without explicit @Value declaration.

Create YourClassProperties with annotation @ConfigurationProperties("some.prefix"):

@ConfigurationProperties("my.example")
public class MyClassProperties {
    private String foo;

    public String getFoo() {
        return foo;
    }

    public void setFoo(String foo) {
        this.foo = foo;
    }
}

Add defined properties to (application).properties:

my.example.foo=bar

And then, in your application you can autowire needed properties...

@Autowired
private MyClassProperties myClassProperties;

... and use them as you would any other properties:

LOG.info("Value of the foo: {}", myClassProperties.getFoo());

Upvotes: 3

user9945564
user9945564

Reputation:

Solve, you need to enable annotation config in configuration file: <context:annotation-config/>

Upvotes: 2

Tristan
Tristan

Reputation: 9141

You need to declare your .properties file using @PropertySource. Not sure it's doable using xml config.

Also, are you sure about this "$", it's "#" in this example : http://forum.spring.io/forum/spring-projects/container/61645-value-and-propertyplaceholderconfigurer

Upvotes: 0

FunkyMan
FunkyMan

Reputation: 309

Remember, your class need a stereotype annotation like @Component or @Service

Upvotes: 8

Related Questions