要使用 @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/