繁体   English   中英

如何从属性文件定义注释的字段值

[英]How to define field value of an annotation from property file

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

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

我只是认为能够从我的application.properties配置destination会很好。 有什么办法吗?

好的,我找到了路。 假设来自application.properties message-consumer.destination属性定义了所需的目的地,那么它就这么简单:

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

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

这是消息使用者。

@Component
public class Consumer implements MessageListener {

    @Override
    public void onMessage(Message message) {

    }
}

这是jms配置:

@Configuration
@EnableJms
public class JmsConfiguration implements JmsListenerConfigurer {

    @Value("${message-consumer.destination}")
    private String destination;

    @Inject
    private MessageListener messageListener;

    @Override
    public void configureJmsListeners(JmsListenerEndpointRegistrar registrar) {
        SimpleJmsListenerEndpoint endpoint = new SimpleJmsListenerEndpoint();
        endpoint.setId("audit.logging");
        endpoint.setDestination(destination);
        endpoint.setMessageListener(messageListener);
        registrar.registerEndpoint(endpoint);
    }

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

Spring文档中对此有一些解释。

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

在资源目录中创建文件“ 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");
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM