2

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?

Eugenio Valeiras
  • 980
  • 1
  • 9
  • 30

1 Answers1

5

@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

Emilien Brigand
  • 9,943
  • 8
  • 32
  • 37