我创建了一个自定义 Java 注释并具有某些属性。如何支持字符串属性的属性占位符?
例如:
Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface PublishEvent {
public EventStore eventStore();
public boolean isPersistent() default false;
public String channelName();
}
我想用作:
@PublishEvent(channelName="${rabbit.event.default}")
public void someMethod(){}
其中rabbit.event.default是application.properties文件中定义的属性的键。我希望将属性键替换为值,就像 spring 的 @Value 注释一样。
我正在使用Spring AOP来拦截注释并进行处理。
最佳答案
我使用org.springframework.util.StringValueResolver#resolveStringValue
解析占位符值的方法。也许下面的示例代码可以帮助您:
@Configuration
public class PublishEventConfiguration implements ApplicationContextAware, EmbeddedValueResolverAware {
private ApplicationContext context;
private StringValueResolver resolver;
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
this.context = context;
}
@Override
public void setEmbeddedValueResolver(StringValueResolver resolver) {
this.resolver = resolver;
}
@PostConstruct
public void init() throws Exception {
Collection<Object> publishEvents = context.getBeansWithAnnotation(PublishEvent.class).values();
for (Object v : publishEvents) {
PublishEvent cfg = v.getClass().getAnnotation(PublishEvent.class);
String channelName = resolver.resolveStringValue(cfg.channelName());
}
}
}
关于java - 如何为java自定义注释提供属性占位符支持,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37918302/