spring - 将文件添加到 Spring Boot 的类路径

标签 spring spring-boot war

我有 server.yml 文件,其中包含仅限 Spring Framework 属性,例如端口号、上下文根路径、应用程序名称。

而且,我有一个 applicationContext.xml ,其中包含以下内容:

<util:properties id="springProperties" location="classpath*:my.properties">
<context:property-placeholder location="classpath*:my.properties"
        local-override="true" properties-ref="springProperties" />

my.properties 文件位于项目的 src/main/resources 目录中。

那么,我可以从我的 java 类访问属性,例如:

@Autowired
@Qualifier("springProperties")
private Properties props; 

public String getProperty(String key){
    return props.getProperty(key);
}

or like `${my.prop}`

当我构建 war 并运行 Spring Boot (java -jar server.war) 时,内部 my.properties 会解析,并且一切都会按预期工作。

但是,我想使用外部 my.properties 覆盖该文件。 我读过https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

我尝试运行类似的东西:

java -jar server.jar --spring.config.location=classpath:/my.properties

java -jar server.jar --spring.config.location=my.properties

但是我可以通过此覆盖的唯一属性来 self 的 server.yml。这意味着,我可以覆盖端口号或应用程序名称。但内部的 my.properties 永远不会受到影响。

我做错了什么吗?我知道外部 my.property 应该位于类路径中,然后它会覆盖内部 my.property 。但这永远不会发生。

最佳答案

您可以使用 @PropertySource({ "classpath:override.properties"}) 从类路径添加额外文件,然后使用环境对象获取值或值的 @Value 注释

@PropertySource({ "classpath:other.properties" })
@Configuration
public class Config{
    @Autowired
    private Environment env; //use env.getProperty("my.prop")

    @Value("${my.prop}")
    private String allowedpatterns;
}

@Component
public OthenClass{

    @Autowired
    //If this class is not component or Spring annotated class then get it from ApplicationContext
    private Environment env; //use env.getProperty("my.prop")

    @Value("${my.prop}")
    private String allowedpatterns;
}

如果您使用 Spring Boot,下面的代码可用于获取 ApplicationContext

ConfigurableApplicationContext ctx = app.run(args);

Environment env = ctx.getBean(Environment.class);

关于spring - 将文件添加到 Spring Boot 的类路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46799055/

相关文章:

java - 未能获得 JDK 11、Spring Boot(包括)的组合。持久性和 JavaFX 工作

grails - Grails WAR构建失败

java - 启动webApp时出现 "Could not resolve placeholder KName"异常

Spring Profiles,不同的 Log4j2 配置

java - 在什么情况下 ApplicationEventPublisher.publishEvent 不会触发?

spring-boot - 相当于 RabbitMq Listener 的 Servlet Filter 是什么?

maven-2 - 如何要求 maven war 插件将特定的 jar 文件复制到 warfile/web-inf/lib

java - 在 Jetty 中部署 jar

java - 连接超时 spring boot 应用程序和 mysql

java - SimpleIdentificResourceAssembler 无法解析为类型