2017-03-04 238 views
0

這裏是我的控制器代碼以獲得豆依賴注入context.getbeans

@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獲得消息,但是當我試圖在運行時從控制器獲取BeanBean時,出現錯誤

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

Bean UserService不是由MqttInboundBeans生成的。 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); .... 
+0

我有一個自動裝配Autowired服務那裏MqttInboundBeans.java,所以如果我是個創設情境戕新的關鍵詞的話,我又怎麼去管理注入了UserService – Rawat

+1

AnnotationConfigApplicationContext依賴只會給你MqttInboundBeans定義的豆子。 ApplicationContext將包含項目中定義的所有bean。 – pkoli