I am learning JMS and different types of brokers out there. I am currently using ActiveMQ (Artemis) for a dummy project.
I currently have Artemis running on the default settings. I can go to the management console and see the queues and topics. I am now creating 2 Java Spring-based apps; one for producing and one for consuming. I have seen few tutorials out there, but I'm getting a NPE, which I'm not sure - why, as I believe I am autowiring the bean correctly.
These are my classes:
Main class:
@SpringBootApplication
public class SpringJmsApplication {
public static void main(String[] args) {
SpringApplication.run(SpringJmsApplication.class, args);
SendMessage send = new SendMessage("This is the test message");
}
}
Sender:
public class Sender {
private static final Logger LOGGER =
LoggerFactory.getLogger(Sender.class);
@Autowired
private JmsTemplate jmsTemplate;
public void send(String message) {
LOGGER.info("sending message='{}'", message);
jmsTemplate.convertAndSend("helloworld.q", message);
}
}
Sender Config:
@Configuration
public class SenderConfig {
@Value("${artemis.broker-url}")
private String brokerUrl;
@Bean
public ActiveMQConnectionFactory senderActiveMQConnectionFactory() {
return new ActiveMQConnectionFactory(brokerUrl);
}
@Bean
public CachingConnectionFactory cachingConnectionFactory() {
return new CachingConnectionFactory(
senderActiveMQConnectionFactory());
}
@Bean
public JmsTemplate jmsTemplate() {
return new JmsTemplate(cachingConnectionFactory());
}
@Bean
public Sender sender() {
return new Sender();
}
}
SendMessage Service:
public class SendMessage {
@Autowired
Sender sender;
public SendMessage(String message){
this.sender.send(message);
}
}
So essentially the error is stemming from the SendMessage class, it's unable to autowire the sender bean but I'm not sure why this error is happening because the Sender bean is being created in the SenderConfig class hence surely Spring should've added it to it Spring container/Bean factory/application context?
This is the stacktrace:
Exception in thread "main" java.lang.NullPointerException
at com.codenotfound.jms.SendMessage.<init>(SendMessage.java:11)
at com.codenotfound.SpringJmsApplication.main(SpringJmsApplication.java:16)