其他分享
首页 > 其他分享> > 如何在Spring的applicationContext中设置JMS配置?

如何在Spring的applicationContext中设置JMS配置?

作者:互联网

如何为下面给出的Java代码设置应用程序?

Hashtable<String, String> properties = new Hashtable<String, String>();
            properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.test.factory");
            properties.put("com.domain", "DevelopmentDomain");
//            properties.put(Context.PROVIDER_URL, "tcp://test:0506");
            properties.put(Context.PROVIDER_URL, "tcp://10.00.0.00:0506");


            properties.put(Context.SECURITY_PRINCIPAL, "aaa");
            properties.put(Context.SECURITY_CREDENTIALS, "aaa");

            javax.naming.Context context = new javax.naming.InitialContext(properties);
            ConnectionFactory factory = (ConnectionFactory) context.lookup("ImpactPocQueueConnectionFactory");

            Connection connection = factory.createConnection();

            connection.start();

            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            Destination queue = session.createQueue("test.producer");

我在这里和那里看到了许多例子,但没有一个给出完整的图片.

解决方法:

如果要将此代码逐字转换为Spring配置,请考虑利用@Configuration方法:

@Bean
public Destination queue() throws JMSException, NamingException {
    return session().createQueue("test.producer");
}

@Bean
public Session session() throws JMSException, NamingException {
    return connection().createSession(false, Session.AUTO_ACKNOWLEDGE);
}

@Bean(initMethod = "start")
public Connection connection() throws JMSException, NamingException {
    return connectionFactory().createConnection();
}

@Bean
public ConnectionFactory connectionFactory() throws NamingException {
    return (ConnectionFactory) context().lookup("ImpactPocQueueConnectionFactory");
}

@Bean
public Context context() throws NamingException {
    return new javax.naming.InitialContext(properties());
}

@Bean
public Hashtable<String, String> properties() {
    Hashtable<String, String> properties = new Hashtable<String, String>();
    properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.test.factory");
    properties.put("com.domain", "DevelopmentDomain");
    //properties.put(Context.PROVIDER_URL, "tcp://test:0506");
    properties.put(Context.PROVIDER_URL, "tcp://10.00.0.00:0506");
    properties.put(Context.SECURITY_PRINCIPAL, "aaa");
    properties.put(Context.SECURITY_CREDENTIALS, "aaa");
    return properties;
}

从技术上讲,你可以使用XML完成所有这些工作,但我发现这种方法更具可读性和可维护性.现在,您可以在范围内使用connectionFactory和队列bean.您可以轻松地与Spring JMS support集成.如果您需要进一步的帮助,请告诉我们.

标签:spring,jms,spring-jms
来源: https://codeday.me/bug/20190729/1572579.html