这是我的控制器代码来获取bean
@RequestMapping("/suscribetest")
@ResponseBody
public String subscribeTest(){
try{
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MqttInboundBeans.class);
MqttPahoMessageDrivenChannelAdapter messageChannel = context.getBean("inbound",MqttPahoMessageDrivenChannelAdapter.class);
messageChannel.addTopic("test", 2);
}catch(Exception ex){
System.out.println("err "+ex.getLocalizedMessage());
}
return "";
}
以下是我的bean类
@Configuration
public class MqttInboundBeans {
@Autowired
private UserService service;
@Bean
public MessageChannel mqttInputChannel() {
return new DirectChannel();
}
@Bean
public MessageProducer inbound() {
MqttPahoMessageDrivenChannelAdapter adapter =
new MqttPahoMessageDrivenChannelAdapter("tcp://localhost:1883", "testClient",
"DATA/#", "LD/#");
adapter.setCompletionTimeout(0);
adapter.setConverter(new DefaultPahoMessageConverter());
adapter.setQos(2);
adapter.setOutputChannel(mqttInputChannel());
return adapter;
}
@Bean
@ServiceActivator(inputChannel = "mqttInputChannel")
public MessageHandler handler() {
return new MessageHandler() {
@Override
public void handleMessage(Message<?> message) throws MessagingException {
System.out.println(message.getHeaders()+" "+message.getPayload());
}
};
}
}
当我尝试运行应用程序时,它工作正常,我可以从messageHandler获取消息,但是当我在运行时尝试从控制器获取getBean时,我收到错误
Error creating bean with name 'mqttInboundBeans': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.ehydromet.service.UserService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
感谢。
答案 0 :(得分:0)
MqttInboundBeans不生成bean UserService。 AnnotationConfigApplicationContext创建Spring Application Context接受输入作为我们使用@Configuration注释的配置类,注册Spring运行时配置类生成的所有bean。 尝试自动连接应用程序上下文,然后从中获取bean。
@Autowired
private ApplicationContext context;
@RequestMapping("/suscribetest") @ResponseBody public String subscribeTest(){
try{
MqttPahoMessageDrivenChannelAdapter messageChannel =(MqttPahoMessageDrivenChannelAdapter) context.getBean("inbound");
messageChannel.addTopic("test", 2); ....