[英]How to init custom annotation in spring
If I define an annotation to set class fields, something like this: 如果定义一个注释来设置类字段,则如下所示:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface Set {
int value();
}
With the necessary reflection: 有必要的反思:
class Injector {
public static void inject(Object instance) {
Field[] fields = instance.getClass().getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(Set.class)) {
Set set = field.getAnnotation(Set.class);
field.setAccessible(true); // should work on private fields
try {
field.set(instance, set.value());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
And I would use it like: 我会像这样使用它:
class Demo {
@Set(1)
public int var;
public int var2;
}
How would I inject this in spring (not spring-boot) at startup? 在启动时如何在春季(而不是春季启动)注入这种东西?
I found the example here but I don't want to call the inject method myself. 我在这里找到了示例,但我不想自己调用inject方法。
You can provide a BeanPostProcessor
to the spring context. 您可以为spring上下文提供
BeanPostProcessor
。
public class Injector implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
inject(bean);
return bean;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.