3种 bean的实例化方式:1默认构造 2静态工厂 3实例工厂(本次只讲静态工厂)
1.默认构造 :一般代码省略 (这里没有笔记 因为比较简单)
<bean id="" class=""> 必须提供默认构造
2静态工厂 :<bean id="" class="工厂的全限定类名(包名加类名)" faction-method="静态方法名 " >
用于生产实例对象的 所有方法都是静态的(static)
常用于spring 整合其他框架和工具的
静态工程的代码:
MyBeanFactory
package c_inject.b_static_factory; public class MyBeanFactory { public static UserService createService(){ return new UserserviceImpl(); } }
bean的配置
<?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"> <!-- 将静态工厂 的实例交给spring class:全限定义类名 factory-method:静态方法名 --> <bean id="userServiceId" class="c_inject.b_static_factory.MyBeanFactory" factory-method="createService" ></bean> </beans>
测试类
package c_inject.b_static_factory; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import a.ioc.Uservice; public class TestStaticFactory { @Test /* * 自定义工厂 */ public void demo01(){ UserService uservice= MyBeanFactory.createService(); uservice.addUser(); }; @Test /* * spring 的工厂 */ public void demo02(){ ApplicationContext application =new ClassPathXmlApplicationContext("c_inject/b_static_factory/beans.xml"); UserService userService = (UserService) application.getBean("userServiceId"); userService.addUser(); }; }