【发布时间】: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