Home > database >  Decorate or Intercept Spring @Autowired Bean
Decorate or Intercept Spring @Autowired Bean

Time:12-12

I am upgrading old Java EE application to Spring based solution. In the old applications there were custom annotations to create proxy inject proxy bean and intercept the method invocation [Interceptor classes implements MethodInterceptor) or (implements InvocationHandler), which used to perform some before and after execution stuff.

We have replaced those custom annotations with Spring marker interfaces like @Service, @Repository etc. and we are able to use @Autowire the bean instances. Now my question is how to intercept these autowired beans to perform per and post execution activities. One solution I can think is to use Spring AOP and use @Around pointcut. Just want to know is there any other and better alternative which can be used like

  1. extending org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor
  2. Using BeanFactoryPostProcessor or BeanPostProcessor.
  3. Using InstantiationAwareBeanPostProcessor

CodePudding user response:

to inject proxy bean and intercept the method invocation [Interceptor classes implements MethodInterceptor) or (implements InvocationHandler), which used to perform some before and after execution stuff

You have to choices

  • integrate this logic now inside your spring bean methods, so there is no before or after method invocation.
  • Continue using before and after method invocation on your now spring bean by effectively using AOP feature of spring.

CodePudding user response:

Use PostConstruct annotation on the method which you wish to execute after bean creation.

import javax.annotation.PostConstruct;
import org.springframework.stereotype.Service;

@Service
public class FooService {
    @PostConstruct
    public void postConstructActivities() {
        //write your code here
    }
}
  • Related