bean管理(xml)
(一)spring的工厂类
FileSystemXmlApplicationContext 读取磁盘配置文件
(二)bean实例化的三种方式
(1)使用类构造器实例化(默认无参数)
1.Bean01.java
package demo01; public class Bean01 { //无参构造函数 public Bean01() { System.out.println("bean1被实例化了..."); } }
2.applicationContext.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!--无参构造器方式--> <bean id="bean01" class="demo01.Bean01"/> </beans>
3.DemoTest.java
package Test; import demo01.Bean01; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class DemoTest { @Test public void demo01(){ //创建工厂 ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml"); //通过工厂创建类 Bean01 bean01=(Bean01)applicationContext.getBean("bean01"); } }
(2)使用静态工厂方法实例化(简单工厂模式)
1.Bean02.java
package demo01; public class Bean02 { }
2.Bean02Factory.java
package demo01; public class Bean02Factory { public static Bean02 bean2(){ System.out.println("bean02被实例化了..."); return new Bean02(); } }
3.applicationContext.xml
<!--静态工厂方式--> <bean id="bean02" class="demo01.Bean02Factory" factory-method="bean2"/>
4.DemoTest.java
@Test public void demo02(){ //创建工厂 ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml"); //通过工厂创建类 Bean02 bean02=(Bean02) applicationContext.getBean("bean02"); }
(3)使用实例工厂方法实例化(工厂方法模式)
1.Bean03.java
package demo01; public class Bean03 { }
2.Bean03Factory.java
package demo01; public class Bean03Factory { public Bean03 bean3(){ System.out.println("bean03被实例化了..."); return new Bean03(); } }
3.applicationContext.xml
<!--实例工厂方式--> <bean id="bean03Factory" class="demo01.Bean03Factory"/> <bean id="bean03" factory-bean="bean03Factory" factory-method="bean3"/>
4.DemoTest.java
@Test public void demo03(){ //创建工厂 ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml"); //通过工厂创建类 Bean03 bean03=(Bean03) applicationContext.getBean("bean03"); }
(三)bean的常用配置
(1)bean的配置
(2)bean的作用域
(四)bean的生命周期