【问题标题】:How to load spring @PropertySource at startup如何在启动时加载弹簧@PropertySource
【发布时间】:2019-06-20 17:50:10
【问题描述】:

我注意到启动期间使用的某些属性只能在application.properties 中设置。

例如:

src/main/java/foo/bar/Foo.java

@SpringBootApplication
public class Foo {

    private static final Logger log = LoggerFactory.getLogger(Foo.class);

    public static void main(String... args) {
        ApplicationContext appContext = SpringApplication.run(Foo.class, args);
        log.info(appContext.getEnvironment().getProperty("spring.profiles.active"));
    }

}

src/main/resources/application.properties

spring.profiles.active=dev

控制台日志:

09:23:48.827 : The following profiles are active: dev
09:23:50.832 : dev

配置文件在启动时被识别为dev,并在Environment 中可用。这是预期的行为。

但是,如果我将同一属性从 application.properties 移动到 foo.properties 并将其加载为 @PropertySource,则行为会发生变化。

src/main/java/foo/bar/FooConfiguration.java

@Configuration
@PropertySource("classpath:foo.properties")
public class FooConfiguration { }

src/main/resources/foo.properties

spring.profiles.active=prod

src/main/resources/application.properties

# empty

控制台日志:

09:35:18.141 : No active profile set, falling back to default profiles: default
09:35:20.175 : prod

在启动期间不考虑配置文件,但在启动后在Environment 上可用。

问题:我如何从@PropertySource 加载属性,并在启动时同时加载其余的application.properties

【问题讨论】:

  • 我认为 @propertySource 是特定于类或 bean 的 Given a file app.properties containing the key/value pair testbean.name=myTestBean, the following @Configuration class uses @PropertySource to contribute app.properties to the Environment's set of PropertySources.
  • 好的,那你为什么不尝试在主类上添加这个PropertySource("classpath:foo.properties") 并尝试一下?
  • @Zack,你有没有在你的 application.properties 中尝试过这个:spring.config.location=file:foo.properties 或 classpath:foo.properties?
  • @Zack 好吧,那是我的疯狂猜测。没关系。我也删除了它,因为其他偶然发现它的人可能会感到困惑,因此您已确认它不起作用,我必须删除该评论。
  • 这可能会提供更多信息stackoverflow.com/questions/43020491/…

标签: java spring spring-boot properties-file


【解决方案1】:

我认为您可以使用“--spring.config.location”属性来指定您要使用的属性文件。

【讨论】:

  • 是的,但这不是只会改变 Spring 找到 application.properties 的位置,而不一定会改变加载其他属性源的行为吗?
  • 是的,它指定了默认的属性文件,如果你使用@PropertySource,所有的字段都会被相应的属性源文件覆盖。
  • 不会的像这样:--spring.config.location=classpath:/default.properties,classpath:/override.properties
  • 不,你不能spring.config.name and spring.config.location are used very early to determine which files have to be loaded, so they must be defined as an environment property (typically an OS environment variable, a system property, or a command-line argument).
猜你喜欢
  • 2018-01-16
  • 2021-01-07
  • 1970-01-01
  • 2018-09-08
  • 1970-01-01
  • 2018-04-27
  • 2016-12-09
  • 1970-01-01
  • 2019-10-21
相关资源
最近更新 更多