类无法访问Spring管理的bean



我有一个Spring配置文件,我在其中定义bean,但不知何故,这个bean无法从同一包中的一个类访问,尽管可以从注释为@Controller的Controller类访问相同的bean。我在想这个班可能不是由Spring管理的,但事实并非如此。1( 配置类

@Bean
public FooConsumer fooConsumer() {
return new FooConsumer();
}
@Bean
public Map<String, ProxyConsumer> appProxyConsumerMap() {
Map<String, ProxyConsumer> proxyConsumer = new HashMap<String, ProxyConsumer>();
proxyConsumer.put(FOO_APP, FooConsumer());
return proxyConsumer;
}
@Bean
public FooEventConsumer fooEventConsumer() {
return new FooEventConsumer();
}
@Bean
public Map<String, FooConsumer> fooConsumerMap(){
Map<String, FooConsumer> fooEventConsumer = new HashMap<String, FooConsumer>();
fooEventConsumer.put(FOO_EVENT, fooEventConsumer());
}

2( 控制器类

@Resource
@Qualifier("appProxyConsumerMap")
Map<String, ProxyConsumer> appProxyConsumerMap;
//proxyApp comes as path variable
ProxyConsumer consumer = appProxyConsumerMap.get(proxyApp); 
//invoke consumer
boolean consumed = consumer.consumeEvent(eventRequest);
//here consumer is my FooConsumer class, till now all works fine.

3( 现在在FooConsumer类中,它试图访问名为fooConsumerMap的Map bean以获取要调用的事件,但不知何故它返回了null。

@Resource
@Qualifier("fooConsumerMap")
Map<String, FooConsumer> fooConsumerMap;
FooEventConsumer consumer = fooConsumerMap.get(eventType);
//Here fooConsumerMap comes as null in this class, though it comes as object in controller class , please advise.

在配置文件中,使用在同一配置中声明的FooConsumerMapbean构造FooConsumerbean。

您可以将其他bean自动连接到配置文件中,但要将文件中的bean组合在一起,您可以将它们作为构造函数参数传递。

请注意,如果您多次调用Bean注释方法,那么即使方法逻辑构造了一个新实例,您也会意外地总是得到相同的实例。

查看文档,网址:https://docs.spring.io/spring-javaconfig/docs/1.0.0.m3/reference/html/creating-bean-definitions.html

最新更新