Sobes.tech
Junior

How to execute the same code after initialization for all beans implementing a certain interface without duplicating @PostConstruct in each?

sobes.tech AI

Answer from AI

To execute the same code after initialization for all beans implementing a specific interface, without duplicating the @PostConstruct annotation in each class, you can use one of the following approaches:

  1. Create a base class with a method annotated with @PostConstruct

    Make an abstract class that implements the interface, and implement the method with @PostConstruct in it. All your beans will inherit from this class and will inherit the behavior.

    public interface MyInterface {
        void doSomething();
    }
    
    public abstract class BaseBean implements MyInterface {
        @PostConstruct
        public void init() {
            // common initialization code
            System.out.println("Common initialization");
        }
    }
    
    @Component
    public class MyBean extends BaseBean {
        @Override
        public void doSomething() {
            // implementation
        }
    }
    
  2. Use BeanPostProcessor

    Create a class implementing BeanPostProcessor, and in the postProcessAfterInitialization method, check if the bean implements the required interface, and execute common code.

    @Component
    public class MyInterfacePostProcessor implements BeanPostProcessor {
        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) {
            if (bean instanceof MyInterface) {
                // common code after initialization
                System.out.println("Common initialization for " + beanName);
            }
            return bean;
        }
    }
    

This approach allows centralized execution of code for all beans with the interface without modifying the beans themselves.

  1. Use Aspect-Oriented Programming (AOP)

    You can write an aspect that triggers after the initialization of a bean with the required interface and executes common code.

The choice of approach depends on specific requirements and project architecture, but BeanPostProcessor is the most flexible and does not require changing the bean classes.

How to execute the same code after initialization for… - sobes.tech