美文网首页
spring依赖注入

spring依赖注入

作者: 李霖神谷 | 来源:发表于2019-11-25 11:44 被阅读0次

    1.构造函数注入
    当容器调用的bean的构造函数是带有参数的,并且这些参数是依赖于其它类是,基于构造函数的注入就完成了。
    带有参数的构造函数的类:

    package com.shuai.hello;
    
    public class Tr {
        private  Te te;
        public Tr(Te te){
            System.out.println("我是Tr的构造函数");
            this.te=te;
        }
        public void print(){
            te.printTe();
        }
    }
    

    需要被依赖的类:

    package com.shuai.hello;
    
    public class Te {
        public  Te(){
            System.out.println("我是Te的构造函数");
        }
        public void printTe(){
            System.out.println("我要打印");
        }
    }
    

    xml中的配置:

    <bean id="Tr" class="com.shuai.hello.Tr">
                    <constructor-arg ref="Te" ></constructor-arg>
            </bean>
            <bean id="Te" class="com.shuai.hello.Te">
            </bean>
    

    测试:只需要获取Tr就可以调用Te的构造方法

       ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
            Tr tr=(Tr) applicationContext.getBean("Tr");
            tr.print();
    

    2.基于设置值的函数依赖注入(set注入):当调用的类存在空参的构造函数,可以通过设置值的形式设置该类的属性值,但是该属性需要set方法。与构造函数不同的是xml配置中是property对值进行注入

    package com.shuai.hello;
    
    public class Tr {
        private  Te te;
        public void print(){
            te.printTe();
        }
    
        public void setTe(Te te) {
        }
    }
     <bean id="Tr" class="com.shuai.hello.Tr">
            <property name="te" ref="Te"></property>
        </bean>
        <bean id="Te" class="com.shuai.hello.Te">
        </bean>
    

    3.通过向xml文件中注入内部bea的形式:

       <bean id="Tr" class="com.shuai.hello.Tr">
            <property name="te" >
                <bean id="te" class="com.shuai.hello.Te" />
            </property>
        </bean>
    

    4.注入集合:list,map,set,配置文件:

     <bean id="collection" class="com.shuai.hello.collection">
            <property name="list">
                <list>
                    <value>list1</value>
                    <value>list2</value>
                    <value>list3</value>
                </list>
            </property>
            <property name="map">
                <map>
                   <entry key="1" value="1"/>
                   <entry key="2" value="2"/>
                   <entry key="3" value="3"/>
                </map>
            </property>
        </bean>
    

    测试

      collection collection= (collection) applicationContext.getBean("collection");
            collection.getList();
            collection.getMap();
    

    相关文章

      网友评论

          本文标题:spring依赖注入

          本文链接:https://www.haomeiwen.com/subject/pbydwctx.html