3
votes

I have a service that sends message to rabbitmq and the consumer do some manipulation of the message and re-queue them.

I can successfully send to rabbitmq the initial message but the problem is i cannot resend to rabbitmq any consumed message if the message requires modifications.

@Service
public class MyService {

    /**
     * The template
     */
    @Autowired
    private AmqpTemplate amqpTemplate;
    private final RabbitMQConfig config;

    public void send(String message) {
        try {
            amqpTemplate.convertAndSend("ex", "r", message);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Then in my config i have setup: @Bean public ConnectionFactory connectionFactory() { /* working code */ }

@Bean
public Queue myQueue() { return new Queue("my-queue"); 
// etc...

@Bean
MessageListenerAdapter myListenerAdapter(MyListener listener) {
    return new MessageListenerAdapter(listener, "listener");
}

@Bean
MyListener myListener() {
    return new MyListener();
}

then...

public class MyListener {
    public void receiveMessage(String message) { 
        // ... some code
        // if message requires modification, then repush
        new Repush().push(message);
    }
}

I tried to create a new class with new but the "myService" always null

@Component
public class Repush {
    @Autowired
    private MyService myService;

    public void push(String message) {
        // myService is null at this point
    }
}
2

2 Answers

2
votes

Don't use new for bean creation. Spring injects fields only in beans. Your MyListener is a bean. Just add Repush field with @Autowired annotation in this class.

public class MyListener {
    @Autowired
    private Repush repush;

    public void receiveMessage(String message) { 
        // ... some code
        // if message requires modification, then repush
        repush.push(message);
    }
}
0
votes

If you declare myService as a bean in the application context as well as Repush as a bean you can then inject it into MyListener using @Autowired.

By creating Repush using new at point-in-time within the listener method, you are not getting a bean that is cognizant of the context you are in.