4

I want to configure my bean String fields through .proprerties file. But it doesn't replace the value key, means it echo "${value}" string. My code below:

Main class:

public class Main {

    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config.xml");
        ValuesContainer valuesContainer = (ValuesContainer) applicationContext.getBean("container");
        System.out.println(valuesContainer.getValue()); //echoes "${value}" instead of Ho-ho-ho!
    }
}

application context:

.....
<context:annotation-config />
<context:component-scan base-package="bean"/>

bean:

package bean;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component("container")
@Scope("singleton")
@PropertySource(value = "classpath:app.properties")
public class ValuesContainer {

    @Value("${value}")
    private String value;

    public String getValue() {
        return value;
    }
}

app.properties:

value = Ho-ho-ho!
VB_
  • 45,112
  • 42
  • 145
  • 293

2 Answers2

2

It looks like you are missing a PropertySourcesPlaceholderConfigurer in your configuration.

See this post.

Community
  • 1
  • 1
Pieter
  • 895
  • 11
  • 22
2

@PropertySource should be used with @Configuration.

You need to create a separate @Configuration class, put your annotation @PropertySource on it and add it to your application context (or let <context:component-scan> to add it).

Alternatively you can configure property sources of your application context programmatically, using Environment.

axtavt
  • 239,438
  • 41
  • 511
  • 482