繁体   English   中英

防止覆盖 application.properties 中的某些属性 - Spring Boot

[英]Prevent overriding some property in application.properties - Spring Boot

我想在我的属性文件中移动一些配置,但出于安全目的,不希望它在运行时被覆盖。 可以在 spring boot 中实现吗?

谢谢,马尼什

像这样的东西应该可以工作,secure.properties 中的任何内容都将无法被覆盖,因为它将被添加到 env 的开头(来自属性文件),无论什么已被覆盖。

@Configuration
public class SecurePropertiesConfig {

    @Autowired
    public void setConfigurableEnvironment(ConfigurableEnvironment env) {
        try {
            final Resource resource = new ClassPathResource("secure.properties");
            env.getPropertySources().addFirst(new PropertiesPropertySource(resource.getFilename(), PropertiesLoaderUtils.loadProperties(resource)));
        } catch (Exception ex) {
            throw new RuntimeException(ex.getMessage(), ex);
        }
    }
}

我尝试了此处发布的 SecurePropertiesConfig 方法,有趣的是,如果我使用 @Value 注释或仅加载环境,属性值会有所不同。 @Value 注释在 setConfigurableEnvironment 方法解析之前解析。 因此,@Value 将解析为直接在类路径中设置的属性文件值,而一旦方法实际运行,环境变量将具有安全(不可覆盖)属性值。 如果我只使用 Environment,它就可以工作,但不幸的是,这使得它对未来使用 @Value 意外更改代码变得有点脆弱,认为它是“安全的”。 我将 SecurePropertiesConfig.java 修改为 ApplicationContextInitializer 以强制它首先加载属性。

安全属性.java

public class SecurePropertiesConfig implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        ConfigurableEnvironment environment = applicationContext.getEnvironment();
        try {
            final Resource resource = new ClassPathResource("secure.properties");
            environment.getPropertySources().addFirst(new PropertiesPropertySource(resource.getFilename(), PropertiesLoaderUtils.loadProperties(resource)));
        } catch (Exception ex) {
            throw new RuntimeException(ex.getMessage(), ex);
        }
    }

然后在您的 application.properties 中添加初始化程序:

context.initializer.classes=package.path.config.SecureProperties

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM