码迷,mamicode.com
首页 > 编程语言 > 详细

spring学习笔记(4)装配Bean 静态工厂 【资源来自网络 版权非本人】

时间:2018-01-07 17:26:54      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:XML   use   pos   方式   encoding   junit   静态方法   blog   return   

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();

        
        
        
        
    };
        
        
             
    }
    

 

spring学习笔记(4)装配Bean 静态工厂 【资源来自网络 版权非本人】

标签:XML   use   pos   方式   encoding   junit   静态方法   blog   return   

原文地址:https://www.cnblogs.com/zhbx/p/8228239.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!