spring: bean初始化和销毁方法

package exm.spring.bean;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class User implements InitializingBean, DisposableBean{
	
	private String name;
	
	private String password;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	/**
	 * 在bean销毁之前调用
	 */
	@Override
	public void destroy() throws Exception {
		
		System.out.println("--------destroy()--------");
	}

	/**
	 * 在bean设值注入之后调用
	 */
	@Override
	public void afterPropertiesSet() throws Exception {
		
		System.out.println("--------afterPropertiesSet()--------");
		
	}
	
	public void initBean()
	{
		System.out.println("<init-method>");
	}
	
	public void destroyBean()
	{
		System.out.println("<destroy-method>");
	}

}



package exm.spring.bean;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
	
	public static void main(String[] args)
	{
		ApplicationContext aac = new ClassPathXmlApplicationContext("bean.xml");
		
		Service service = aac.getBean("service", Service.class);
		
		//每次从Service得到的User都不一样
		System.out.println(service.createUser());
		System.out.println(service.createUser());
		
		((ClassPathXmlApplicationContext)aac).close();
	}
}


<!-- 配置文件 -->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:p="http://www.springframework.org/schema/p"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
        
        <bean id="user" class="exm.spring.bean.User" scope="prototype" init-method="initBean" destroy-method="destroyBean">
        </bean>
        
        <!-- 如果要在Service中每次获得User,则在配置中User不要注入到Service -->
        <bean id="service" class="exm.spring.bean.Service">
        </bean>
        
</beans>


你可能感兴趣的:(spring: bean初始化和销毁方法)