主要是:init-method=”init” 和destroy-method=”destroy”这两个方法 实现BeanPostProcessor接口,然后在配置文件中配置,类似于过拦截器的作用
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns ="http://www.springframework.org/schema/beans"
xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p ="http://www.springframework.org/schema/p"
xsi:schemaLocation ="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" >
<bean id ="person" class ="com.hgh.spring.lifecycle.Person"
p:age ="12" p:city ="shangsi" p:name2 ="dst" init-method ="init"
destroy-method ="destroy" > </bean >
<bean class ="com.hgh.spring.lifecycle.MyBeanPostProcessor" > </bean >
</beans >
package com.hgh.spring.lifecycle;
public class Person {
private String name;
private int age;
private String city;
public String getName () {
return name;
}
public void setName2 (String name) {
this .name = name;
}
public int getAge () {
return age;
}
public void setAge (int age) {
this .age = age;
}
public String getCity () {
return city;
}
public void setCity (String city) {
this .city = city;
}
public Person (String name, int age, String city) {
super ();
this .name = name;
this .age = age;
this .city = city;
}
public Person () {
super ();
}
@Override
public String toString () {
return "Person [name=" + name + ", age=" + age + ", city=" + city + "]" ;
}
public void init (){
System.out.println("init" );
}
public void destroy (){
System.out.println("destroy" );
}
}
package com .hgh .spring .lifecycle
import org.springframework .context .ApplicationContext
import org.springframework .context .support .ClassPathXmlApplicationContext
public class Main {
public static void main(String[] args) {
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("bean-lifecycle.xml" )
Person person = (Person) ac.getBean ("person" )
System.out .println (person)
ac.close ()
}
}