private String name;
private int age;
public Person(){
System.out.println("--------|| 构造方法在调用...");
this.name = "默认用户名";
this.age= 250;
System.out.println(this);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
return "Person{" +
"name='" + name + '/'' +
", age=" + age +
'}';
}
public void init(){
System.out.println("--------|| init()正在调用...");
this.name="init";
this.age=998;
System.out.println(this);
}
public void afterPropertiesSet() throws Exception {
System.out.println("--------|| afterPropertiesSet()正在调用...");
this.age=999;
System.out.println(this);
}
public void destroy() throws Exception {
System.out.println("--------|| destroy()正在调用...");
}
}
private static ApplicationContext _instance;
static {
if (_instance == null) _instance = buildApplicationContext();
}
private BeanContextHelper() {
}
/**
* 重新构建ApplicationContext对象
*
* @return ApplicationContext
*/
public static ApplicationContext buildApplicationContext() {
return new ClassPathXmlApplicationContext("applicationContext.xml");
}
/**
* 获取一个ApplicationContext对象
*
* @return ApplicationContext
*/
public static ApplicationContext getApplicationContext() {
return _instance;
}
}
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="person" class="com.lavasoft.springnote.ch01.Person" init-method="init" destroy-method="destroy">
<property name="name">
<value>lavasoft</value>
</property>
<property name="age">
<value>22</value>
</property>
</bean>
</beans>
* Created by IntelliJ IDEA.<br>
* <b>User</b>: leizhimin<br>
* <b>Date</b>: 2008-4-17 16:58:07<br>
* <b>Note</b>: 客户端测试
*/
public class Test {
public static void main(String args[]) {
Test test = new Test();
test.test();
}
public void test(){
ApplicationContext context = BeanContextHelper.getApplicationContext();
Person person = (Person) context.getBean("person");
System.out.println("--------|| 从Spring BeanFactory获取person...");
System.out.println(person);
}
}
log4j:WARN No appenders could be found for logger (org.springframework.core.CollectionFactory).
log4j:WARN Please initialize the log4j system properly.
Person{name='默认用户名', age=250}
--------|| afterPropertiesSet()正在调用...
Person{name='lavasoft', age=999}
--------|| init()正在调用...
Person{name='init', age=998}
--------|| 从Spring BeanFactory获取person...
Person{name='init', age=998}
Process finished with exit code 0
只有一个方法void setBeanName(String name),用来设置bean的名字.
DisposableBean
为Bean的销毁提供回调功能,在bean实例销毁前调用接口的destroy()方法.
InitializingBean
Spirng的InitializingBean为bean提供了定义初始化方法的方式。InitializingBean是一个接口,它仅仅包含一个方法:afterPropertiesSet()。