如何从属性文件

时间:2016-10-27 09:36:35

标签: java spring jms

我正在使用spring和activemq并使用以下方法从消息代理接收消息:

@JmsListener(destination = "sample.queue")
public void receiveQueue(String text) {
    System.out.println(text);
}

我认为能够从我的destination配置application.properties会很高兴。有没有办法做到这一点?

3 个答案:

答案 0 :(得分:5)

好的,我找到了方法。假设来自message-consumer.destination的{​​{1}}属性定义了所需的目标,那么它就像这样简单:

application.properties

以下是关于如何外部化队列目标的旧想法:

这是消息使用者。

@JmsListener(destination = "${message-consumer.destination}")
public void receiveQueue(String text) {
    System.out.println(text);
}

这是jms配置:

@Component
public class Consumer implements MessageListener {

    @Override
    public void onMessage(Message message) {

    }
}

答案 1 :(得分:0)

我认为您不能为此添加变量,但即使您认为更好的解决方案是使用DestinationResolver,因为这是destination的用途。

Spring documentation中有一些解释。

答案 2 :(得分:0)

可以通过在类级别读取属性文件来实现:

在资源目录中创建文件'my.properties':

destination = sample.queue

包装类:

public class MyProperties {

    private static final RespourceBundle BUNDLE = RespourceBundle.getBundle("/my.properties");

    public static String destination() {
        return BUNDLE.getProperty("destination");
    }
}

然后改变你的代码:

@JmsListener(destination = MyProperties.destination())
public void receiveQueue(String text) {
    System.out.println(text);
}

没有测试过,但我认为这应该有用。

编辑:我确定我以前在注释中使用过常量。也许这种静态方法导致了问题。试试这个:

public class MyProperties {

    private static final RespourceBundle BUNDLE = RespourceBundle.getBundle("/my.properties");

    public static final String DESTINATION = BUNDLE.getProperty("destination");

}

@JmsListener(destination = MyProperties.DESTINATION)
public void receiveQueue(String text) {
    System.out.println(text);
}

编辑:最后一次尝试

public class MyProperties {

    private static final RespourceBundle BUNDLE = RespourceBundle.getBundle("/my.properties");

    public static final String DESTINATION;

    static {
        DESTINATION = BUNDLE.getProperty("destination");
    }

}
相关问题