Search code examples
springdependency-injectionjavabeans

Dependency injection with context.getbeans


here is my controller code to get 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 "";
    }

and following is my bean class

@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());

        }

    };
}
}

when i am trying to run the application it works fine and i can get the messages from messageHandler but when i am trying to getBean from controller at run time i am getting error

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: {}

Thanks.


Solution

  • The bean UserService is not generated by MqttInboundBeans. AnnotationConfigApplicationContext creates Spring Application Context accepting input as our configuration class annotated with @Configuration, registering all the beans generated by the configuration class in Spring runtime. Try auto wiring application context, and then get bean from it.

    @Autowired
    private ApplicationContext context;
    @RequestMapping("/suscribetest") @ResponseBody public String subscribeTest(){ 
    try{ 
     MqttPahoMessageDrivenChannelAdapter messageChannel =(MqttPahoMessageDrivenChannelAdapter) context.getBean("inbound");
    
    
    messageChannel.addTopic("test", 2); ....