java - 用于类变量的 Spring Boot 自定义解析器
问题描述
我正在尝试实现这样的目标:
@Controller
public SomeController {
@CustomConfig("var.a")
private String varA;
@CustomConfig("var.b")
private String varB;
@RequestMapping(value = "/", method = RequestMethod.GET)
public String get() {
return varA;
}
}
CustomConfig 将是一个接受一个值参数的@Interface 类。我们不使用 @Value 的原因是它不是来自配置文件而是来自 API(例如https://getconfig.com/get?key=var.a)。所以我们要发出 HTTP 请求来注入它。
到目前为止,如果 varA 和 varB 作为参数在 get() 方法内部,我只能通过在扩展的类中使用下面的方法来使某些东西起作用WebMvcConfigurerAdapter
:
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
CustomConfigResolver resolver = new CustomConfigResolver();
argumentResolvers.add(resolver);
}
在 CustomComfigResolver.resolveArgument() 中,我们将执行 HTTP 查询,但这并不是我们真正想要的,我们需要将其作为类变量注入。
有没有人有在类变量级别解决它的经验?
谢谢
解决方案
如果您使用 @Value 而不是您自己的自定义注释,这可能会起作用。这使用内置环境:
@Order(Ordered.HIGHEST_PRECEDENCE)
@Configuration
public class TcpIpPropertySourceConfig implements InitializingBean {
@Autowired
private ConfigurableEnvironment env;
@Autowired
private RestTemplate rest;
public void afterPropertiesSet() {
// Call your api using Resttemplate
RemoteProperties props = //Rest Call here;
// Add your source to the environment.
MutablePropertySources sources = env.getPropertySources();
sources.addFirst(new PropertiesPropertySource("customSourceName", props)
}
}
当你开始考虑“不愉快”的场景时,你想要达到的目标就很困难了。服务器关闭/无法访问。您需要在上述方法中考虑所有这些。
我强烈建议改用 Spring Cloud Config。很棒的指南在这里:https ://www.baeldung.com/spring-cloud-configuration
这提供了: - 重新加载您的 @Value() 属性,因此不需要自定义注释。- 开箱即用的更稳定的服务器和出色的 Spring 集成。
最重要的是,如果配置服务器出现故障,很容易应用重试和退避(请参阅https://stackoverflow.com/a/44203216/2082699)。这将确保您的应用程序不会在服务器不可用时崩溃。
推荐阅读
- java - Exoplayer 2.10.3 用java实现
- kubernetes - 从 k8s 和 helm 漂移中恢复
- python - 保持需要一段时间加载的库的方式,使用 virtualenv 类型的会话解决方案加载
- http - 哪个 HTTP 状态代码应指示由于无效输入而未能执行某些代码?
- flutter - 弹出直到没有更多根(即退出应用程序)
- javascript - 取消选中单个复选框时所有复选框都未选中-react redux
- vb.net - ComboBox 无法从 KeyValuePair 转换为 Integer
- java - 创建侦听点时出现 Jain SIP 错误
- php - 如何在 Composer 中强制依赖库的版本
- spring - 为什么当我使用 JsonIdentityInfo 时,我只在第一次出现查询返回值时才检索我父母的实体数据?