java - 如何保护@ConfigurationProperties 类免受更改?

标签 java spring spring-boot configurationproperty

要使用 @ConfigurationProperties 注解,必须创建一个带有 getter 和 setter 的类:

@ConfigurationProperties(prefix = "some")
public class PropertiesConfig {
    private boolean debug;

    public boolean isDebug() {
        return debug;
    }

    public void setDebug(boolean debug) {
        this.debug = debug;
    }
}

但这会导致有人试图通过调用来修改此值的情况:

@Autowire
private PropertiesConfig config;        
//....

config.setDebug(true);

有没有一种方法可以创建没有 setter 和外部解析器/读取器类的 @ConfigurationProperties 注释类?

最佳答案

一种尽可能少样板代码的方法是使用仅包含 getter 的接口(interface)

public interface AppProps {
    String getNeededProperty();
}

并在 Lombok 的 @Getter@Setter 注释的帮助下在实现中摆脱样板 getter 和 setter:

@ConfigurationProperties(prefix = "props")
@Getter
@Setter
public class AppPropsImpl implements AppProps {
    private String neededProperty;
}

然后,为了让其他 bean 只能通过接口(interface)访问 bean bo,可以不将其标记为 @Component 或使用 @EnableConfigurationProperties(AppPropsImpl.class) 在主应用程序类上,考虑将其放入将通过接口(interface)公开的配置中:

@Configuration
@EnableConfigurationProperties
public class PropsConfiguration  {
    @Bean
    public AppProps appProps(){
        return new AppPropsImpl();
    }
}

现在这个 bean 只能通过使用接口(interface)来注入(inject),这使得 setter 对其他 bean 不可用:

public class ApplicationLogicBean {
    @Autowired
    AppProps props;

    public void method(){
        log.info("Got " + props.getNeededProperty());
    }
}

使用 Spring Boot 1.5.3 和 Lombok 1.16.16 进行测试。

关于java - 如何保护@ConfigurationProperties 类免受更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44732752/

相关文章:

java - 将纬度和经度值(度)转换为 Double 。 java

spring - 在两个不同的文件中定义 spring security http 元素?

java - 查询失败,错误代码为 13,服务器本地主机 :27017 上的错误消息为 'command find requires authentication'

java - springrabbitmq和UI层或托管bean

Spring Boot OAuth2 和 Oracle IDCS : JWK Set URI responds with 401 UNAUTHORIZED, 需要 token

java - 从日期字符串获取java中的日期对象

java - 请帮助...我在 Java 中计算素数的实现是否在做它应该做的事情?

java - 使用 Astyanax 突变批处理将 Map 插入 Cassandra CQL3 列族

java - 是否可以在 Spring Boot 中读取响应的正文?

java - 异常: Caused by: org. springframework.beans.factory.BeanCreationException:创建名称为 'httpPutFormContentFilter'的bean时出错