[JAVAEE] 实验03:Spring Bean的配置、实例化、作用域、生命周期与装配方式

【一】实验目的:

(1)掌握Bean的实例化
(2)掌握Bean的装配方式
(3)掌握Bean的作用域和生命周期

【二】结构:

1️⃣配置(不具体介绍)
2️⃣实例化:构造方法实例化(最常用)、静态工厂实例化、实例工厂实例化
3️⃣作用域
4️⃣生命周期
5️⃣装配方式

【三】实验代码:

##一、实例化

 BeanClass.java
package instance;
//一、bean的构造方法之 实例化(最常用)
public class BeanClass {	
	public String message;
	public BeanClass() {
		message = "构造方法实例化Bean";
	}
	public BeanClass(String s) {
		message = s;
	}
}
BeanInstanceFactory.java
package instance;
public class BeanInstanceFactory {
	public BeanClass createBeanClassInstance() {
	    return new BeanClass("调用实例工厂方法实例化Bean");
	}
}

BeanStaticFactory.java

package instance;
//二、bean实例化之 静态工厂实例化
public class BeanStaticFactory {
	
	private static BeanClass beanInstance = new BeanClass("调用静态工厂方法实例化Bean");
	public static BeanClass createInstance() {
        return beanInstance;
    }
}

配置文件:ApplicationContext.xml

	
	
	
	
	
    
    
    
    
    

测试:TestInstance.java

package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import instance.BeanClass;
public class TestInstance {
	public static void main(String[] args) {
		//初始化spring容器,通过路径加载配置文件
		@SuppressWarnings("resource")
		ApplicationContext appCon = new ClassPathXmlApplicationContext("applicationContext.xml");
		//一、构造方法的
		BeanClass b1 = (BeanClass)appCon.getBean("constructorInstance");
		System.out.println(b1 + "------" + b1.message);
		
		//二、静态工厂的
		BeanClass b2 = (BeanClass)appCon.getBean("staticFactoryInstance");
		System.out.println(b2+ "------" +b2.message);
		
		//三、实例工厂的
		BeanClass b3 = (BeanClass)appCon.getBean("instanceFactoryInstance");
		System.out.println(b3+ "------" +b3.message);
		
	}
}

你可能感兴趣的:(前端开发之路,javaee)