您的位置:首页 > 编程语言 > Java开发

Sping学习笔记(2)----实例化Bean的三种方式

2015-06-17 10:32 239 查看
Spring的实例化Bean有三种方式:

 使用类构造器直接实例化

 使用静态工厂的方法实例化

 使用实例工厂方法实例化

 

三种方式对应的配置如下

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"  

        xmlns:context="http://www.springframework.org/schema/context"  

        xmlns:tx="http://www.springframework.org/schema/tx"  

        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  

                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd   

                http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">  

        <!-- 使用类构造器直接实例化 -->     

        <bean id="userBean1" class="com.szy.spring.implbean.UserBean" />  

        <!-- 使用静态工厂的方法实例化 -->  

        <bean id="userBean2" class="com.szy.spring.factory.BeanFactory" factory-method="UserBeanService" />  

        <!-- 使用实例工厂方法实例化 -->  

        <bean id="factory" class="com.szy.spring.factory.BeanFactory" />  

        <bean id="userBean3" factory-bean="factory" factory-method="getUserBeanService" />  

</beans>  

 

其中BeanFactory类的代码如下

Java代码

package com.szy.spring.factory;
  

  

import com.szy.spring.implbean.UserBean;   

import com.szy.spring.interfacebean.PersonBean;   

  

public class BeanFactory
  

{   

    //使用静态工厂的方法实例化使用   

    public static PersonBean UserBeanService()
  

    {   

        return new UserBean();
  

    }   

       

    public PersonBean getUserBeanService()   

    {   

        return new UserBean();
  

    }   

}  

在这三种方式中我们最常用的还是第一种。

spring.rar (2.6 MB)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring 基础