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

    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();
    
            
            
            
            
        };
            
            
                 
        }
        
  • 相关阅读:
    mybatis 插件的原理-责任链和动态代理的体现
    优雅的对象转换解决方案-MapStruct使用进阶(二)
    将博客搬至CSDN
    python headers missing
    Gvim:unable to load python
    gvim keil 快捷跳转至出现错误(警告)行
    stm32 堆溢出
    keil在线烧录突然提示 No target connected #
    cygwin vim can't write .viminfo
    切换用户后,/etc/profile的配置不起效
  • 原文地址:https://www.cnblogs.com/zhbx/p/8228239.html
Copyright © 2011-2022 走看看