java 将动态参数传递给注释?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12568385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing dynamic parameters to an annotation?
提问by Nicholas DiPiazza
I am using the following annotation:
我正在使用以下注释:
@ActivationConfigProperty(
propertyName = "connectionParameters",
propertyValue = "host=127.0.0.1;port=5445,host=127.0.0.1;port=6600"),
public class TestMDB implements MessageDrivenBean, MessageListener
I would like to pull each of these IP addresses and ports and store them in a file jmsendpoints.properties
... then load them dynamically. Something like this:
我想提取这些 IP 地址和端口中的每一个并将它们存储在一个文件中jmsendpoints.properties
……然后动态加载它们。像这样的东西:
@ActivationConfigProperty(
propertyName = "connectionParameters",
propertyValue = jmsEndpointsProperties.getConnectionParameters()),
public class TestMDB implements MessageDrivenBean, MessageListener
Is there a way to do that?
有没有办法做到这一点?
回答by Johan Sj?berg
No.The annotation processor (the annotation-based framework you're using) needs to implement an approach to handling placeholders.
不可以。注释处理器(您正在使用的基于注释的框架)需要实现一种处理占位符的方法。
As an example, a similar technique is implemented in Spring
例如,类似的技术在 Spring
@Value("#{systemProperties.dbName}")
Here Spring
implements an approach to parsingthat particular syntax, which in this case translates to something similar to System.getProperty("dbName");
HereSpring
实现了一种解析该特定语法的方法,在这种情况下转换为类似于System.getProperty("dbName");
回答by FThompson
Annotations are not designed to be modifiable at runtime, but you might be able to utilize a bytecode engineering library such as ASMin order to edit the annotation values dynamically.
注释不是为了在运行时可修改而设计的,但您可以利用字节码工程库(例如ASM)来动态编辑注释值。
Instead, I recommend creating an interface in which you could modify these values.
相反,我建议创建一个界面,您可以在其中修改这些值。
public interface Configurable {
public String getConnectionParameters();
}
public class TestMDB implements MessageDrivenBean, MessageListener, Configurable {
public String getConnectionParameters() {
return jmsEndpointsProperties.getConnectionParameters();
}
//...
}
You might wish to create a more key-value oriented interface, but that's the general concept of it.
您可能希望创建一个更面向键值的界面,但这是它的一般概念。