V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
RedBeanIce
V2EX  ›  自言自语

111

  •  
  •   RedBeanIce · 2022-09-11 23:14:12 +08:00 · 556 次点击
    这是一个创建于 598 天前的主题,其中的信息可能已经有所发展或是发生改变。

    111

    请删除这个帖子

    yanghanlin
        1
    yanghanlin  
       2022-09-11 23:22:37 +08:00   ❤️ 1
    private static RestTemplate REST_TEMPLATE = (RestTemplate) SpringUtil.getBean( ...

    这里 SpringUtil.getBean 运行时 ApplicationContext 还未建立起来,自然无法获取到 bean
    RedBeanIce
        2
    RedBeanIce  
    OP
       2022-09-11 23:22:57 +08:00
    @yanghanlin yes 您是对的。
    RedBeanIce
        3
    RedBeanIce  
    OP
       2022-09-11 23:25:23 +08:00
    @yanghanlin 但是我不知道有什么办法解决这个问题,这个问题是在 static 的地方,引入 spring 的非 static 对象,,我去尝试一下。,,有一点思路。

    感谢您的回复
    RedBeanIce
        4
    RedBeanIce  
    OP
       2022-09-11 23:38:28 +08:00   ❤️ 1
    @yanghanlin

    这样就行了!!感谢!!!

    ```java
    @Component
    public class RestTemplateUtil implements ApplicationListener<ApplicationStartedEvent>, ApplicationContextAware {

    private static RestTemplate REST_TEMPLATE;
    private ApplicationContext applicationContext;

    private RestTemplateUtil() {
    }

    public void setApplicationContext(ApplicationContext inputApplicationContext) throws BeansException {
    this.applicationContext = inputApplicationContext;
    }

    public void onApplicationEvent(ApplicationStartedEvent event) {
    RestTemplate restTemplate = (RestTemplate)this.applicationContext.getBean("xuegao-framework-restTemplate", RestTemplate.class);
    setRestTemplate(restTemplate);
    log.info("[xue-gao-framework][RestTemplateUtil][onApplicationEvent][设置 restTemplate 完毕]");
    }

    public static void setRestTemplate(RestTemplate restTemplate) {
    if (REST_TEMPLATE == null) {
    REST_TEMPLATE = restTemplate;
    }
    }

    ```
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2370 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 13:00 · PVG 21:00 · LAX 06:00 · JFK 09:00
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.