【问题标题】:Java Sprint-Boot : Not able to access @Bean defined in @ConfigurationJava Spring-Boot:无法访问@Configuration中定义的@Bean
【发布时间】:2020-05-22 02:42:30
【问题描述】:

我在 Spring-boot 配置(用 @Configuration 注释)类中定义了一个这样的 Bean:

@Bean
public MyRegistry myRegistry() {
    return new MyRegistry();
}

MyRegistry 看起来像这样:

@Component
@Getter
@Setter
public class MyRegistry {
    Map<String, Object> resourcesMap = new HashMap<>();

    public MyRegistry() {
        resourcesMap.put("handler1", new MyHandler1());
        resourcesMap.put("handler2", new MyHandler2());
    }
}

现在,在另一个带有 @Component 的类中,我有 @Autowired myRegistry 并按如下方式使用它:

MyHandler1 handler1 = new ObjectMapper().convertValue(myRegistry.getResourcesMap().get("handler1"), MyHandler1.class);

我在启动 Spring-Boot 应用程序时没有收到任何错误,但是当应用程序运行时,无法访问 Handler1 的方法。

想了解我在这里做错了什么。因为我是 Spring-Boot 的新手,所以我可能搞砸了注释的使用

【问题讨论】:

  • 因为您将对象存储在地图中而不是您使用的原因:new ObjectMapper().convertValue ?
  • 直接投射不起作用
  • 你为什么要发明自己的MyRegistry?这通常是 Spring 为您完成的工作。
  • 您能否告诉我们更多有关您的用例的信息。除了 Spring Boot 提供的应用程序上下文之外,您似乎还创建了另一个应用程序上下文。我重做了一个和你类似的,顺便说一句,它对我有用。

标签: java spring spring-boot annotations


【解决方案1】:

那么下面的代码(sn-p1)有效吗?

Object mHandler1Obj = myRegistry.getResourcesMap().get("handler1", MyHandler1.class);

但是当你尝试(sn-p2)时它失败了:

MyHandler1 handler1 = new ObjectMapper().convertValue(myHandler1Obj);

如果是这样,那么spring boot在这里就无关紧要了,“sn-p1”工作的事实已经表明spring boot已经完成了它的工作。

现在它的 objectmapper 无法将通用对象转换为 MyHandler1...

为了重现它,请尝试从方程式中“排除”弹簧靴并仅检查 sn-p2

顺便说一句,这个 BTW 可以解释为什么应用程序上下文(spring boot 应用程序)无例外地启动:如果它不能自动装配某些东西,它会在启动期间失败,但正如你所解释的那样......

【讨论】:

    【解决方案2】:

    您已经使用@Component 将 MyRegistry 定义为 bean,除非您想创建多个 bean,否则无需使用 @Configuration 创建 bean。

    我尝试了下面的代码并且它正在工作,我希望它会有所帮助。

    MyRegistry.java

    @Component
    public class MyRegistry {
    
       private Map<String, Object> resource = new HashMap<>();
    
        public MyRegistry() {
            this.resource.put("handler", new MyHandler());
        }
    
        public Map<String, Object> getResource() {
            return resource;
        }
    }
    

    MyHandler.java

    public class MyHandler {
    
        private String message;
    
        public MyHandler() {
            this.message = "Hello world";
        }
    }
    

    TestBean.java

    @Autowired
    private MyRegistry myRegistry;
    
    @Override
    public void test() throws Exception {
       MyHandler handler = new ObjectMapper().convertValue(myRegistry.getResource().get("handler"), MyHandler.class);
        System.out.printf("message "+ handler.getMessage());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-27
      • 2021-03-01
      • 1970-01-01
      • 2020-08-26
      • 1970-01-01
      • 2016-09-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多