依赖注入3种方式(xml实现)

构造器注入

构造器注入依赖于构造方法实现,而构造方法可以是有参和无参的

比如有构造器为:

public Test(String id,String name){
    this.id = id ;
    this.name = name ;
}

xml配置可以为

<bean id = "test1" class = "相对项目的路径">
    <!--index为参数的位置,value为要注入的值-->
    <!--当参数为对象的时候,使用为ref = "对象的id"-->
    <constructor-arg index = "0" value = "xx"/>
    <constructor-arg index = "1" value = "yy"/>
</bean>

  采用构造器注入,实现是非常简单的,,但是缺点是,对于参数多的情况,就显得很麻烦了,这个时候就应该考虑一下setter注入了。

setter注入

setter注入是Spring中注入最为主流的方式,灵活且可读性高。

xml配置可以为

<bean id = "test1" class = "相对项目的路径">
    <!--name为成员变量的名字,value为要注入的值-->
    <!--当参数为对象的时候,使用为ref = "对象的id"-->
    <property name = "id" value = "xx"/>
    <property name = "name" value = "yy"/>
</bean>

接口注入

接口注入分为两种,一种是对外部资源,比如

<bean id="dataSource1" class="jdbc连接类">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/test" />
    <property name="username" value="root" />
    <property name="password" value="***" />
</bean>

对于自定义的接口实现

public interface A{
}

public class B impliment A{
    String id;
} 

对于自定义的接口A,注入到B这个对象中

<bean id = "aInterface" calss = "**/A"/>
<bean id = "b" class = "**/B">
     <property name="aInterface">
        <ref local="aInterface"/>
    </property>  
</bean>

这样配置注入就可以在IOC容器中通过反射获取实例了。

猜你喜欢

转载自blog.csdn.net/weijifeng_/article/details/80044494