【问题标题】:Properties file not loading in Spring-batch属性文件未在 Spring-batch 中加载
【发布时间】:2020-02-13 00:55:57
【问题描述】:

我正在尝试使用注释加载属性:

@PropertySource({"classpath:application.properties"})

@Value("${my.property}")
String myProperty;

因此,myProperty 始终为 null

在使用时:

BatchConfiguration.class.getClassLoader().getResourceAsStream("application.properties");

这是我的 Batch conf 类签名:

@Configuration
@ComponentScan
@EnableBatchProcessing
@PropertySource({"classpath:application.properties"})
public class BatchConfiguration {

    @Value("${db.url}")
    private String url;
...

}

和Application.java:

@SpringBootApplication
public class Application {

    public static void main(String[] args) throws Exception {
            SpringApplication.run(Application.class, args);
        }
}

我也尝试使用以下方式加载它:

    @Autowired
    public static Environment env;

但是 env 也是空的。

【问题讨论】:

  • 你能分享你的属性文件的位置吗?
  • Spring Boot 已经加载了application.properties,无需手动尝试再次加载。你不能注入static变量。
  • 我删除了static@PropertySource,仍然无法正常工作
  • 你不需要@PropertySource,因为 Spring Boot 已经加载了该文件。如果是null,那是因为您自己正在创建该类的实例。如果 Spring 会这样做,您的应用程序将无法启动,因为它无法解析属性。

标签: java spring spring-boot spring-batch


【解决方案1】:

在运行 Spring 启动应用程序时传递以下 JVM 参数

--spring.config.location=properties file path

【讨论】:

    【解决方案2】:

    在您的 @PropertySource({"classpath:application.properties"}) 中删除 {} 应该是

    @PropertySource("classpath:application.properties")
    

    @PropertySource(value="classpath:application.properties")
    

    【讨论】:

    • value@PropertySource 属性是String[],所以{} 是有效的。
    • 是的@KarthikeyanVaithilingam,你当然是对的。虽然我会使用 PropertySources 或只是可重复的注释,但 {} 确实有效
    猜你喜欢
    • 1970-01-01
    • 2014-04-08
    • 2015-04-04
    • 2016-11-16
    • 1970-01-01
    • 2013-01-15
    • 1970-01-01
    • 1970-01-01
    • 2014-10-05
    相关资源
    最近更新 更多