类变量的Spring引导自定义解析器



我正在努力实现这样的目标:

@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)。这将确保你的应用程序不会在服务器不可用时崩溃。

最新更新