关键代码:
<!-- 生命周期--> <bean id="user" class="com.shuoeasy.test.User" p:id="1001" p:name="说易事" init-method="init" destroy-method="destroy"> </bean> <!-- 配置bean的后置处理器,实现BeanPostProcessor接口,不需要配置id --> <bean class="com.shuoeasy.test.MyBeanPostProcessor"></bean>
详细:
一、生命周期
User.java:
package com.shuoeasy.test; public class User { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; System.out.println("设置属性id"); } public String getName() { return name; } public void setName(String name) { this.name = name; System.out.println("设置属性name"); } public User(){ System.out.println("构造函数"); } public void init(){ System.out.println("初始化"); } public void destroy(){ System.out.println("销毁"); } @Override public String toString() { return "User [id=" + id + ", name=" + name + "]"; } }
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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 生命周期--> <bean id="user" class="com.shuoeasy.test.User" p:id="1001" p:name="说易事" init-method="init" destroy-method="destroy"> </bean> </beans>
Main.java:
package com.shuoeasy.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml"); User user = (User) ctx.getBean("user"); System.out.println("user->" + user); } }
输出:
构造函数
设置属性id
设置属性name
初始化
user->User [id=1001, name=说易事]
二、后置处理器:
bean.xml加上bean配置
<!-- 配置bean的后置处理器,实现BeanPostProcessor接口,不需要配置id --> <bean class="com.shuoeasy.test.MyBeanPostProcessor"></bean>
输出:
构造函数
设置属性id
设置属性name
初始化后:User [id=1001, name=说易事],user
初始化
初始化前:User [id=1001, name=说易事],user
user->User [id=1001, name=说易事]