myborobudur
myborobudur

Reputation: 4435

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.

Upvotes: 1

Views: 782

Answers (1)

Dean Xu
Dean Xu

Reputation: 4681

You can provide a BeanPostProcessor to the spring context.

public class Injector implements BeanPostProcessor {
  @Override
  public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    inject(bean);
    return bean;
  }
}

Upvotes: 2

Related Questions