首页 > 解决方案 > 用于类变量的 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 查询,但这并不是我们真正想要的,我们需要将其作为类变量注入。

有没有人有在类变量级别解决它的经验?

谢谢

标签: javaspring-boot

解决方案


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


推荐阅读