其他分享
首页 > 其他分享> > SpringIOC注入

SpringIOC注入

作者:互联网

1.手动注入:set注入,构造器注入,静态工厂注入,实例化工厂注入

1.1 set注入

在类中需要别的bean/基本数据类型,需要设置对应的set方法

public class UserService {
    //bean类型注入
    private dao1 dao1;
    public void setDao1(dao1 dao1){
        this.dao1=dao1;
    }

    //基本类型注入
    private String data;
    public void setData(String data){
        this.data=data;
    }

    //集合注入
    private List<String> list;
    public void setList(List<String> list){
        this.list=list;
    }
    public void printList(){
        list.forEach((v -> System.out.println(v)));
    }


    public void test(){
        System.out.println("UserService.test");
        dao1.test();

        System.out.println(data);

        printList();
    }
}

在spring.xml对应的bean标签中设置property属性

<?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
                            https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--set方法注入
            name:属性字段名字
            ref:bean标签的id
            value:具体值 -->
    <bean id="UserService" class="com.xxx.service.UserService">
<!--        bean对象-->
        <property name="dao1" ref="dao1"></property>
<!--        基本类型-->
        <property name="data" value="lwxlwx"></property>
<!--        集合注入-->
        <property name="list">
            <list>
                <value>list1</value>
                <value>list2</value>
            </list>
        </property>
    </bean>

    <bean id="dao1" class="com.xxx.dao.dao1"></bean>


</beans>

标签:SpringIOC,void,list,dao1,data,public,注入
来源: https://www.cnblogs.com/lwx11111/p/16442469.html