javaEE Spring,Spring配置之Bean元素进阶,scope属性(单例、多例),生命周期属性(init-method、destroy-method)

 

Test.java(测试类):

package cn.xxx.demo;

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

import cn.xxx.bean.User;

public class Test {
	
	@Test
	//scope:singleton 单例
	//scope:prototype 多例
	public void fun1(){
		//1 创建容器对象
		ApplicationContext ac = new ClassPathXmlApplicationContext("cn/itcast/b_create/applicationContext.xml");
		//2 向容器"要"user对象
		User u1 = (User) ac.getBean("user");
		User u2 = (User) ac.getBean("user");
		
		System.out.println(u1==u2);//单例:true  多例:false
	}
	
	@Test
	//测试生命周期方法
	public void fun2(){
		//1 创建容器对象
		ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("cn/itcast/b_create/applicationContext.xml");
		//2 向容器"要"user对象
		User u = (User) ac.getBean("user");
		//3 打印user对象
		System.out.println(u);
		//强行关闭容器,触发销毁方法
		ac.close();
	}
}

src/applicationContext.xml(Spring配置文件,配置Bean元素):




	
	

User.java(Spring容器管理的Bean对象):

package cn.xxx.bean;

public class User {
	
	
	public User() {
		System.out.println("User对象空参构造方法!!!!");
	}

	private String name;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	public void init(){
		System.out.println("我是初始化方法!");
	}

	public void destroy(){
		System.out.println("我是销毁方法!");
	}
	
}

 

 

你可能感兴趣的:(javaEE,java,javaee,Spring配置,scope)