Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Value with @PropertySource("classpath:application.properties") allways return null [duplicate]

application.properties

local=true

AppConfig.java

    @PropertySource("classpath:application.properties")
    @Configuration
    public class AppConfig {
        @Value("${local}")
        private Boolean local;

        @Bean
        public DataSource dataSource() {
            DriverManagerDataSource dataSource = new DriverManagerDataSource();

            if(local){
              [..]
            } else {
              [..]
            }

            return dataSource;
        }
    }

    @Bean
    public PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

HibernateUtil.class

@PropertySource("classpath:application.properties")
public class HibernateUtil {
    static {
        try {
            Properties prop= new Properties();

            if(local){
              [..]
            } else {
              [..]
            }
}

I need to config my DB locally or remotely and I cant. "local in Hibernate.class" Always return null. Why?

like image 339
Eugenio Valeiras Avatar asked Jan 23 '26 12:01

Eugenio Valeiras


1 Answers

@PropertySource("classpath:application.properties") is an annotation to load your properties file when the application context of Spring is loaded, so it should be used in a configuration class, you need @Configuration like:

@Configuration
@PropertySource("classpath:application.properties")
public class AppConfig {
}

and you need an extra piece of code, to declare a static bean PropertySourcesPlaceholderConfigurer:

@Configuration
@PropertySource("classpath:application.properties")
public class AppConfig {

  @Value("${local}")
  private Boolean local;

  //Used in addition of @PropertySource
  @Bean
  public static PropertySourcesPlaceholderConfigurer   propertySourcesPlaceholderConfigurer() {
      return new PropertySourcesPlaceholderConfigurer();
  }

}

it helps to resolve @Value and the ${...} placeholder, see: http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/support/PropertySourcesPlaceholderConfigurer.html

like image 138
Emilien Brigand Avatar answered Jan 25 '26 01:01

Emilien Brigand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!