zoukankan      html  css  js  c++  java
  • spring学习笔记(5)装配Bean 实例工厂 【资源来自网络 版权非本人】

    实例工厂:必须现有工厂的实例对象,通过实例对象创建对象。所有的方法都是非静态的(这一点和静态工厂有区别)

    (直接看代码)

      工厂(和静态工厂的区别就是非静态 其他都一样)

    package c_inject.c_factory;
    /*
     * 实例工厂
     */
    public class MyBeanFactory {
     public  UserService createService(){
        return new UserserviceImpl();
     } 
    }

      配置(配置和静态的有点区别  仔细看看吧 )

    <?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="MyBeanFactoryId" class="c_inject.c_factory.MyBeanFactory">
          <!-- 获取userService 
          factory-bean :确定工厂实例
          factory-method : 确定工厂中的方法
          -->
          <bean id="userServiceId" factory-bean="MyBeanFactoryId" factory-method="createService"></bean>
    </beans>

       测试类 (静态自定义和实例自定义的区别大一点  当用spring的时候完全一样)

    package c_inject.c_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(){
            //自定义实例工厂
            //1.创建工厂
            MyBeanFactory factory=new MyBeanFactory();
            //通过工厂获取对象
            UserService uservice= factory.createService();
            uservice.addUser();
            };
            
        @Test    
        /*
         * spring 的工厂
         */
        public void demo02(){
            ApplicationContext application =new ClassPathXmlApplicationContext("c_inject/c_factory/beans.xml");
            UserService userService = (UserService) application.getBean("userServiceId");
            userService.addUser();
    
            
            
            
            
        };
            
            
                 
        }
        
  • 相关阅读:
    软工作业01 P18 第四题
    自我介绍
    进行代码复审训练
    源代码管理工具调查
    软工作业PSP与单元测试训练
    进行代码复审训练
    源代码管理工具
    软工作业PSP与单元测试训练
    作业
    第一堂课
  • 原文地址:https://www.cnblogs.com/zhbx/p/8228318.html
Copyright © 2011-2022 走看看