在bean 实例化时,进行某种操作,可以继承`BeanPostProcessor`,缺点是每创建一个bean都会执行 postProcessBeforeInitialization()和postProcessAfterInitialization() 方法
@Service public class Test1ServiceImpl implements BeanPostProcessor,Test1Service{ @Override public void test1() { System.out.println("test1"); } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { System.out.println("postProcessBeforeInitialization"); return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System.out.println("postProcessAfterInitialization"); return bean; } }
推荐使用 ApplicationContextAware
@Service public class Test2ServiceImpl implements ApplicationContextAware,Test2Service{ @Override public void test2() { System.out.println("test2"); } @Override public void setApplicationContext(ApplicationContext arg0) throws BeansException { System.out.println("setApplicationContext"); } }