1 public class SpringBean implements InitializingBean , DisposableBean, BeanNameAware, BeanFactoryAware, BeanClassLoaderAware { 2 3 public SpringBean () { 4 System.out. println ( "SpringBean 构造方法 :" + studentService); 5 System.out. println ( "SpringBean 构造方法 " ); 6 } 7 8 @Autowired 9 StudentServiceImpl studentService; 10 11 @Override 12 public void afterPropertiesSet () throws Exception { 13 System.out. println ( "afterPropertiesSet" ); 14 } 15 16 @Override 17 public void destroy () throws Exception { 18 System.out. println ( "destroy" ); 19 } 20 21 @Override 22 public void setBeanClassLoader (ClassLoader classLoader) { 23 System.out. println ( "setBeanClassLoader" ); 24 } 25 26 @Override 27 public void setBeanFactory (BeanFactory beanFactory) throws BeansException { 28 System.out. println ( "setBeanFactory" ); 29 } 30 31 @Override 32 public void setBeanName (String name) { 33 System.out. println ( "setBeanName:" + studentService); 34 System.out. println ( "setBeanName" ); 35 } 36 37 public void initMethod () { 38 System.out. println ( "initMethod" ); 39 } 40 41 public void destroyMethod () { 42 System.out. println ( "destroyMethod" ); 43 } 44 }再定义一个BeanPostProcessor,在重写的两个方法中进行了判断,如果传进来的beanName是 springBean才进行打印:
1 @Component 2 public class MyBeanPostProcessor implements BeanPostProcessor { 3 @Override 4 public Object postProcessBeforeInitialization (Object bean, String beanName) throws BeansException { 5 if (beanName. equals ( "springBean" )) { 6 System.out. println ( "postProcessBeforeInitialization" ); 7 } 8 return bean; 9 } 10 11 @Override 12 public Object postProcessAfterInitialization (Object bean, String beanName) throws BeansException { 13 if (beanName. equals ( "springBean" )) { 14 System.out. println ( "postProcessAfterInitialization" ); 15 } 16 return bean; 17 } 18 }
定义一个配置类,完成自动扫描,但是SpringBean是手动注册的,并且声明了initMethod和 destroyMethod:
@Configuration 2 @ComponentScan 3 public class AppConfig { 4 @Bean(initMethod = "initMethod" ,destroyMethod = "destroyMethod" ) 5 public SpringBean springBean () { 6 return new SpringBean (); 7 } 8 }
最后就是启动类了:
1 public static void main (String[] args) { 2 AnnotationConfigApplicationContext annotationConfigApplicationContext = 3 new AnnotationConfigApplicationContext (AppConfig. class ); 4 annotationConfigApplicationContext. destroy (); 5 }
运行结果:
1 SpringBean 构造方法 : null 2 SpringBean 构造方法 3 setBeanName : com.codebear.StudentServiceImpl@31190526 4 setBeanName 5 setBeanClassLoader 6 setBeanFactory 7 postProcessBeforeInitialization 8 afterPropertiesSet 9 initMethod 10 postProcessAfterInitialization 11 destroy 12 destroyMethod
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)