依赖注入方式:Spring支持两种依赖注入方式,分别是属性注入和构造函数注入。还有工厂方法注入方式。
依赖注入还分为:注入依赖对象可以采用手工装配自动装配,在实际应用开发中建议使用手工装配,因为自动装配会产生许多未知情况,开发人员无法预见最终的装配结果。
手工装配依赖对象又分为3种方式:
1、编程方式(写的过程中向BeanFactory去注册)
2、是在XML文件中,通过在bean节点下配置;如上面讲到的使用属性的setter方法注入依赖对象和使用构造器方法注入依赖对象都是这种方式。
3、就是在java代码中使用注解的方式进行装配,在代码中加入@Resource或者@Autowired等,怎样使用注解的方式来为某个bena注入依赖对象呢?
自动装配依赖对象分为2种方式:
1、配置文件的bean中增加autowire
2、也可以选择在beans中加入default-autowire属性,为所有bean设置默认自动装配

Spring中提供了自动装配依赖对象的机制,但是在实际应用中并不推荐使用自动装配,因为自动装配会产生未知情况,开发人员无法预见最终的装配结果。

自动装配是在配置文件中实现的,如下:

<bean id="***" class="***" autowire="byType">

只需要配置一个autowire属性即可完成自动装配,不用再配置文件中写<property>,但是在类中还是要生成依赖对象的setter方法。

Autowire的属性值有如下几个:

· byType 按类型装配  可以根据属性类型,在容器中寻找该类型匹配的bean,如有多个,则会抛出异常,如果没有找到,则属性值为null;

· byName 按名称装配  可以根据属性的名称在容器中查询与该属性名称相同的bean,如果没有找到,则属性值为null;

· constructor 与byType方式相似,不同之处在与它应用于构造器参数,如果在容器中没有找到与构造器参数类型一致的bean,那么将抛出异常;

· autodetect 通过bean类的自省机制(introspection)来决定是使用constructor还是byType的方式进行自动装配。如果发现默认的构造器,那么将使用byType的方式。

 
---------------分割线-----------------------------------------------------------------------------------------------------
示例:
一、使用属性setter方法注入
 
下面是Bean和beans-config.xml文件。

public class HelloBean {  

    private String helloWord; 

    //...省略getter、setter方法     

}

xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="helloBean"
class="onlyfun.caterpillar.HelloBean">
<property name="helloWord">
<value>Hello!Justin!</value>
</property>
</bean>
</beans>

java:

public class SpringDemo {
public static void main(String[] args) {
Resource rs = new FileSystemResource("beans-config.xml");
BeanFactory factory = new XmlBeanFactory(rs); HelloBean hello = (HelloBean) factory.getBean("helloBean");
System.out.println(hello.getHelloWord());
}
}
二、使用constructor方式完成注入
其中xml配置有如下方式:
在配置文件中配置该类的bean,并配置构造器,在配置构造器中用到了<constructor-arg>节点,该节点有四个属性:

· index是索引,指定注入的属性,从0开始,如:0代表personDao,1代表str属性;

· type是指该属性所对应的类型,如Persondao对应的是com.aptech.dao.PersonDAO;

· ref 是指引用的依赖对象;

· value 当注入的不是依赖对象,而是基本数据类型时,就用value;

 java代码:
public class HelloBean {
private String name;
private String helloWord; // 建议有要无参数建构方法
public HelloBean() {
} public HelloBean(String name, String helloWord) {
this.name = name;
this.helloWord = helloWord;
} //...省略getter、setter方法
}

xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="helloBean"
class="onlyfun.caterpillar.HelloBean">
<constructor-arg index="0">
<value>Justin</value>
</constructor-arg>
<constructor-arg index="1">
<value>Hello</value>
</constructor-arg>
</bean>
</beans>

java代码:

public class SpringDemo {
public static void main(String[] args) {
ApplicationContext context =
new FileSystemXmlApplicationContext("beans-config.xml"); HelloBean hello = (HelloBean) context.getBean("helloBean");
System.out.print("Name: ");
System.out.println(hello.getName());
System.out.print("Word: ");
System.out.println(hello.getHelloWord());
}
}
三、属性参考
 
public class HelloBean {  
    private String helloWord;  
    private Date date;  
     
    //...省略getter、setter方法     
}
 
<beans>  
    <bean id="dateBean" class="java.util.Date"/>  
    <bean id="helloBean" class="onlyfun.caterpillar.HelloBean">  
        <property name="helloWord">  
            <value>Hello!</value>  
        </property>  
        <property name="date">  
            <ref bean="dateBean"/>  
        </property>  
    </bean>  
</beans>
 
public class SpringDemo {  
    public static void main(String[] args) {  
        ApplicationContext context =  
            new FileSystemXmlApplicationContext("beans-config.xml"); 
          
        HelloBean hello = (HelloBean) context.getBean("helloBean"); 
        System.out.print(hello.getHelloWord()); 
        System.out.print(" It's "); 
        System.out.print(hello.getDate()); 
        System.out.println("."); 
    }  
}
 
四、“byType”自动绑定
 
将“三”中的配置文件改为下面,即可完成bean属性的按类型自动绑定。
 
<beans>  
    <bean id="dateBean" class="java.util.Date"/>  
    <bean id="helloBean" class="onlyfun.caterpillar.HelloBean" autowire="byType">  
        <property name="helloWord">  
            <value>Hello!</value>  
        </property>  
    </bean>  
</beans>
 
五、“byName”自动绑定
 
将“三”中的配置文件改为下面,即可完成bean属性的按名称自动绑定。
 
<beans>  
    <bean id="dateBean" class="java.util.Date"/>  
    <bean id="helloBean" class="onlyfun.caterpillar.HelloBean" autowire="byName">  
        <property name="helloWord">  
            <value>Hello!</value>  
        </property>  
    </bean>  
</beans>
 
六、“constructor”自动绑定
 
将“三”中的配置文件改为下面,即可完成bean属性的按构造方法自动绑定。在建立依赖关系时,Srping容器会试图比对容器中的Bean实例类型,及相关的构造方法上的参数类型,看看在类型上是否符合,如果有的话,则选用该构造方法来建立Bean实例。如果无法绑定,则抛出org.springframework.beans.factory.UnsatisfiedDependencyException异常。
 
<beans>  
    <bean id="dateBean" class="java.util.Date"/>  
    <bean id="helloBean" class="onlyfun.caterpillar.HelloBean" autowire="constructor">  
        <property name="helloWord">  
            <value>Hello!</value>  
        </property>  
    </bean>  
</beans>
 
七、“autodetect”自动绑定
 
将“三”中的配置文件改为下面,即可完成bean属性的自动绑定,这个自动绑定是Spring会尝试用入constructor来处理依赖关系的建立,如果不行,则再尝试用byType类建立依赖关系。
 
<beans>  
    <bean id="dateBean" class="java.util.Date"/>  
    <bean id="helloBean" class="onlyfun.caterpillar.HelloBean" autowire="autodetect">  
        <property name="helloWord">  
            <value>Hello!</value>  
        </property>  
    </bean>  
</beans>
 
八、依赖检查方式
 
在自动绑定中,由于没办法从定义文件中,清楚地看到是否每个属性都完成设定,为了确定某些依赖关系确实建立,您可以假如依赖检查,在<bean>标签使用时设定"dependency-check",可以有四种依赖检查方式:simple、objects、all、none。
 
simple:只检查简单的类型(像原生数据类型或字符串对象)属性是否完成依赖关系,。
objects:检查对象类型的属性是否完成依赖关系。
all:则检查全部的属性是否完成依赖关系。
none:设定是默认值,表示不检查依赖性。
 
<beans>  
    <bean id="dateBean" class="java.util.Date"/>  
    <bean id="helloBean" class="onlyfun.caterpillar.HelloBean" autowire="autodetect" dependeny-check="all">  
        <property name="helloWord">  
            <value>Hello!</value>  
        </property>  
    </bean>  
</beans>
 
九、集合对象注入
 
对于像数组、List、Set、Map等集合对象,在注入前必须填充一些对象至集合中,然后再将集合对象注入至所需的Bean时,也可以交由Spring的IoC容器来自动维护或生成集合对象,并完成依赖注入。
 
public class SomeBean { 
    private String[] someStrArray; 
    private Some[] someObjArray; 
    private List someList; 
    private Map someMap;

public String[] getSomeStrArray() { 
        return someStrArray; 
    } 
    public void setSomeStrArray(String[] someStrArray) { 
        this.someStrArray = someStrArray; 
    } 
    public Some[] getSomeObjArray() { 
        return someObjArray; 
    } 
    public void setSomeObjArray(Some[] someObjArray) { 
        this.someObjArray = someObjArray; 
    } 
    public List getSomeList() { 
        return someList; 
    } 
    public void setSomeList(List someList) { 
        this.someList = someList; 
    } 
    public Map getSomeMap() { 
        return someMap; 
    } 
    public void setSomeMap(Map someMap) { 
        this.someMap = someMap; 
    } 
}

 
public class Some { 
    private String name;

public String getName() { 
        return name; 
    } 
    public void setName(String name) { 
        this.name = name; 
    } 
    public String toString() { 
        return name; 
    } 
}

 
<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"  
  "http://www.springframework.org/dtd/spring-beans.dtd">

<beans> 
    <bean id="some1" class="onlyfun.caterpillar.Some"> 
        <property name="name"> 
            <value>Justin</value> 
        </property> 
    </bean> 
     
    <bean id="some2" class="onlyfun.caterpillar.Some"> 
        <property name="name"> 
            <value>momor</value> 
        </property> 
    </bean> 
     
    <bean id="someBean" class="onlyfun.caterpillar.SomeBean"> 
        <property name="someStrArray"> 
            <list> 
                <value>Hello</value> 
                <value>Welcome</value> 
            </list> 
        </property> 
         
        <property name="someObjArray"> 
            <list> 
                 <ref bean="some1"/> 
                 <ref bean="some2"/> 
            </list> 
        </property> 
         
        <property name="someList"> 
            <list> 
                 <value>ListTest</value> 
                 <ref bean="some1"/> 
                 <ref bean="some2"/> 
            </list> 
        </property> 
         
        <property name="someMap"> 
            <map> 
                 <entry key="MapTest"> 
                     <value>Hello!Justin!</value> 
                 </entry> 
                 <entry key="someKey1"> 
                     <ref bean="some1"/> 
                 </entry> 
            </map> 
        </property> 
    </bean>  
</beans>

 
public class SpringDemo {  
    public static void main(String[] args) {  
        ApplicationContext context =  
            new FileSystemXmlApplicationContext( 
                    "beans-config.xml"); 
          
        SomeBean someBean =  
            (SomeBean) context.getBean("someBean"); 
         
        // 取得数组型态依赖注入对象 
        String[] strs =  
            (String[]) someBean.getSomeStrArray(); 
        Some[] somes =  
            (Some[]) someBean.getSomeObjArray(); 
        for(int i = 0; i < strs.length; i++) { 
            System.out.println(strs[i] + ","  
                    + somes[i].getName()); 
        }

// 取得List型态依赖注入对象 
        System.out.println(); 
        List someList = (List) someBean.getSomeList();  
        for(int i = 0; i < someList.size(); i++) { 
            System.out.println(someList.get(i)); 
        } 
         
        // 取得Map型态依赖注入对象 
        System.out.println(); 
        Map someMap = (Map) someBean.getSomeMap(); 
        System.out.println(someMap.get("MapTest")); 
        System.out.println(someMap.get("someKey1")); 
    }  
}

 

十、静态工厂的方法注入

静态工厂顾名思义,就是通过调用静态工厂的方法来获取自己需要的对象,为了让spring管理所有对象,我们不能直接通过"工程类.静态方法()"来获取对象,而是依然通过spring注入的形式获取:
同样看关键类,这里我需要注入一个FactoryDao对象,这里看起来跟第一种注入一模一样,但是看随后的xml会发现有很大差别:
Spring的IOC配置文件,注意看<bean name="staticFactoryDao">指向的class并不是FactoryDao的实现类,而是指向静态工厂DaoFactory,并且配置 factory-method="getStaticFactoryDaoImpl"指定调用哪个工厂方法:

十一、实例工厂的方法注入

实例工厂的意思是获取对象实例的方法不是静态的,所以你需要首先new工厂类,再调用普通的实例方法:
那么下面这个类没什么说的,跟前面也很相似,但是我们需要通过实例工厂类创建FactoryDao对象:
最后看spring配置文件:
 
 

Spring Bean基本管理--bean注入方式汇总的更多相关文章

  1. (转)让Spring自动扫描和管理Bean

    http://blog.csdn.net/yerenyuan_pku/article/details/52861403 前面的例子我们都是使用XML的bean定义来配置组件.在一个稍大的项目中,通常会 ...

  2. Spring中bean的四种注入方式

    一.前言   最近在复习Spring的相关内容,这篇博客就来记录一下Spring为bean的属性注入值的四种方式.这篇博客主要讲解在xml文件中,如何为bean的属性注入值,最后也会简单提一下使用注解 ...

  3. spring Bean的三种注入方式

    1.构造函数注入: 构造函数的注入方式分为很多种 (1)普通构造函数,空参数的构造函数 <bean id="exampleBean" class="examples ...

  4. Spring第八发—自动装配及让Spring自动扫描和管理Bean

    依赖注入–自动装配依赖对象(了解即可) 对于自动装配,大家了解一下就可以了,实在不推荐大家使用.例子: byName:按名称装配,可以根据属性的名称,在容器中寻找跟该属性名相同的bean,如果没有找到 ...

  5. Spring是如何管理Bean

    容器是什么?spring中是如何体现的?一直有疑惑,这两天看了一下Spring管理bean的Demo,对于Spring中的容器有了简单的认识. 我们知道,容器是一个空间的概念,一般理解为可盛放物体的地 ...

  6. Spring、Spring自动扫描和管理Bean

    Spring2.5为我们引入了组件自动扫描机制,它可以在类路径下寻找标记了@Component.@Service.@Controller.@Repository注解的类,并把这些类纳入到spring容 ...

  7. Spring IOC以及三种注入方式

    IOC是spring的最基础部分,也是核心模块,Spring的其他组件模块和应用开发都是以它为基础的.IOC把spring的面向接口编程和松耦合的思想体现的淋漓尽致. IOC概念 IOC(Invers ...

  8. Spring中Ioc容器的注入方式

    1 通过setter方法注入 bean类: package com.test; public class UserServiceImplement implements IUserService { ...

  9. Spring常用的三种注入方式

    好文要收藏,摘自:https://blog.csdn.net/a909301740/article/details/78379720 Spring通过DI(依赖注入)实现IOC(控制反转),常用的注入 ...

随机推荐

  1. 【hadoop2.6.0】一句话形容mapreduce

    网上看到的: We want to count all the books in the library. You count up shelf #1, I count up shelf #2. Th ...

  2. SpringMVC学习总结(五)——SpringMVC文件上传例子

    这是用的是SpringMVC-3.1.1.commons-fileupload-1.2.2和io-2.0.1 首先是web.xml <?xml version="1.0" e ...

  3. Xamarin.Android 入门之:Android API版本设置

    一.引言 Xamarin.Android有几个Android API级别设置,确定多个版本的Android应用程序的兼容性.本博客解释了这些设置意味着什么,如何配置它们,以及它们在运行时对您的应用程序 ...

  4. python os.stat() 和 stat模块详解

    stat 系统调用时用来返回相关文件的系统状态信息的. 首先我们看一下stat中有哪些属性: >>> import os >>> print os.stat(&qu ...

  5. Android:创建Android工程

    创建Android工程,在Eclipse左栏右键 new->project..   (版本不一样,名字会有所区别) 然后选择Android下的Android application projec ...

  6. Hibernate配置文件hbm主键的generator可选项

    Hibernate配置文件hbm主键的generator可选项 1.自动增长identity 适用于MySQL.DB2.MS SQL Server,采用数据库生成的主键,用于为long.short.i ...

  7. Hibernate学习笔记(1)

    1 使用Hibernate (1)创建User Library,命名为HIBERNATE3,加入需要的jar (2)创建hibernate配置文件hibernate.cfg.xml, 为了便于调试最好 ...

  8. 整理了一份招PHP高级工程师的面试题

    1. 基本知识点 HTTP协议中几个状态码的含义:1xx(临时响应) 表示临时响应并需要请求者继续执行操作的状态代码. 代码   说明 100   (继续) 请求者应当继续提出请求. 服务器返回此代码 ...

  9. Docker实例教程[超详细](一)

    Docker Docker 是一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的容器中,然后发布到任何流行的 Linux 机器上,也可以实现虚拟化.容器是完全使用沙箱机制,相互 ...

  10. Java内部类总结 分类: 原理 2015-06-28 09:51 9人阅读 评论(0) 收藏

    内部类是指在一个外部类的内部再定义一个类.内部类作为外部类的一个成员,并且依附于外部类而存在的. 内部类可为静态,可用protected和private修饰(而外部类只能使用public和缺省的包访问 ...