创建User类
public class User2 {
private Integer userid;
private String username;
private String password;
public User2() {
System.out.println("第一步:调用构造方法");
}
public User2(Integer userid, String username, String password) {
this.userid = userid;
this.username = username;
this.password = password;
}
public void initUser() {
System.out.println("第四步:调用初始化方法");
}
public void destroyUser() {
System.out.println("第五步:调用销毁方法");
}
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
System.out.println("第二步:给属性赋值");
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User2{" +
"userid=" + userid +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
public class MyBeanProcessor implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("bean初始化之前调用");
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("bean初始化之后调用");
return bean;
}
}
创建xml文件
<?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"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="user2" class="com.maliqiang.bean.User2" init-method="initUser" destroy-method="destroyUser">
<property name="username" value="小明"></property>
</bean>
<!-- 调用初始化方法 之前和之后 -->
<bean id="myBeanProcessor" class="com.maliqiang.bean.processor.MyBeanProcessor"></bean>
</beans>
创建测试类
public class Test06 {
@Test
public void testGetBean1() {
// ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext6.xml");
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext6.xml");
User2 user2 = applicationContext.getBean("user2", User2.class);
System.out.println("user2 = " + user2);
// 调用销毁方法要调用子类的close方法
applicationContext.close();
}
}