java - @Value 和 @PropertySource ("classpath:application.properties")始终返回 null

标签 java spring config

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 {
              [..]
            }
}

我需要在本地或远程配置我的数据库,但我不能。 “Hibernate.class 中的本地”始终返回 null。 为什么?

最佳答案

@PropertySource("classpath:application.properties") 是一个注解,用于在加载Spring的应用程序上下文时加载您的属性文件,因此它应该在配置类中使用,您需要@Configuration 例如:

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

并且您需要一段额外的代码来声明静态 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();
  }

}

它有助于解析@Value和${...}占位符,请参阅:http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/support/PropertySourcesPlaceholderConfigurer.html

关于java - @Value 和 @PropertySource ("classpath:application.properties")始终返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33016434/

相关文章:

java.io.FileNotFoundException : (Read-only file system) Mac

windows - 用本地配置文件替换 Microsoft.VC90.CRT WinSxS 策略文件

Java - 从 Java.lang.Object 到自定义类实例的类型转换

javascript - ModelAndView 不重定向,但给出正确的响应

java - 使用Spring Controller 处理错误404

emacs - 有没有办法将 .emacs 更改应用到所有 emacs 客户端而无需重新启动 emacs 守护进程?

java - 使用命令行运行程序和配置文件

java - 在 Hashcode 中搜索在 Java 中不起作用

java - 在Java中使用startsWith和endsWith时如何忽略大小写?

Java 程序结构建议