2

I am trying to read value from application properties into a class annotated with

@Configuration
public class testClass {

  @Value("${com.x.y.z.dummy.name}")
  private String name;

once I run the code at a method in this class annotated with @Bean:

  @Bean
  public Helper helper(X x){
     System.out.println(this.name);
  }
        

Here the output is -> ${com.x.y.z.dummy.name} instead of the value of ${com.x.y.z.dummy.name} in the application.properties . I tried @Autowired and tried reading from environment variable too. Not sure what might be happening. Could anyone help with this? Adding application.properties:

com.x.y.z.dummy.name=localhost
com.x.y.z.dummy.host=8888
İsmail Y.
  • 3,579
  • 5
  • 21
  • 29
dojacat
  • 27
  • 8

1 Answers1

1

I would suggest to search in your project for a Bean that returns a PropertySourcesPlaceholderConfigurer. That object could be configured to set a different prefix instead of "${". Doing so would result in the behavior that you are describing.

For example, creating this class I was able to reproduce your problem.

import org.springframework.context.annotation.Bean;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

public class PrefixConfiguration {

    @Bean
    public static PropertySourcesPlaceholderConfigurer configure(){
        PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer
                = new PropertySourcesPlaceholderConfigurer();
        propertySourcesPlaceholderConfigurer.setPlaceholderPrefix("%{");
        propertySourcesPlaceholderConfigurer.setIgnoreUnresolvablePlaceholders(true);
        return propertySourcesPlaceholderConfigurer;
    }
}

Your Bean could be different, and it could be there for a good reason, so don't blindly delete it without further investigation.

gere
  • 1,600
  • 1
  • 12
  • 19
  • 1
    Thank you @gere , I don't see the PropertySourcesPlaceholderConfigurer at all , I am facing this problem post an upgrade of a dependency which is a third party . Once I added the PropertySourcesPlaceholderConfigurer it seems to be working fine – dojacat Feb 21 '21 at 18:43
  • 1
    Then the `PropertySourcesPlaceholderConfigurer` is configured inside the third party library in a way that changes the normal behavior. When you add it yourself, you are declaring it again, and doing so, make it work normally again. – gere Feb 21 '21 at 20:08
  • Hey why should this -> static PropertySourcesPlaceholderConfigurer configure() be a static method ? Could you please help me understand ? – dojacat Feb 22 '21 at 17:57
  • 1
    Because the Spring docs suggest to do so: look here for the paragraph "BeanFactoryPostProcessor-returning @Bean methods": https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Bean.html it explains why and it uses a bean returning exactly the PropertySourcesPlaceholderConfigurer as an example. – gere Feb 23 '21 at 07:59