1.通过@Bean(initMethod ="initPerson",destroyMethod ="destroyPerson" ) public class Person { public Person() { System.out.println("Person 初始化............"); } public void initPerson(){ System.out.println("Person ..... init"); } public void destroyPerson(){ System.out.println("Person ..... destroy"); } } 2.@PostConstruct 和 @PreDestroy public class Pig { public Pig() { System.out.println("Pig 被创建了....."); } @PostConstruct public void initPig(){ System.out.println("Pig ..... init"); } @PreDestroy public void destroyPig(){ System.out.println("Pig ..... destroy"); } } 3.实现InitializingBean和DisposableBean 接口 public class Cat implements InitializingBean,DisposableBean{ public Cat() { System.out.println("Cat .... 被初始化了"); } @Override public void afterPropertiesSet() throws Exception { System.out.println("cat ...init"); } @Override public void destroy() throws Exception { System.out.println("cat ...destroy"); } } @Import({Cat.class,Pig.class}) public class Configue { @Bean(initMethod ="initPerson",destroyMethod ="destroyPerson" ) public Person person(){ return new Person(); } } public class App { public static void main( String[] args ) { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Configue.class); applicationContext.close(); } }
理解这三种方式,对于源码学习有一定的帮助