Spring(DI)

DI(Dependency Injection)即依赖注入,对象之间的依赖由容器在运行期决定,即容器动态的将某个依赖注入到对象自重

基于XML配置注入依赖

有参构造函数注入依赖

bean类实现有参构造函数

public class Student {
    private Integer id;
    private String name;

    /**
     * 有参构造函数
     */
    public Student(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

在配置文件中配置参数通过有参构造函数给对象属性赋值

<!--通过有参构造注入依赖-->
    <bean id="student3" class="com.tulun.Spring.IOC.pojo.Student">
        <!--id属性注入-->
        <constructor-arg name="id" value="11"/>
        <!--name属性注入-->
        <constructor-arg name="name" value="图论"/>
    </bean>

有参构造是使用constructor-arg标签

set方法注入依赖

给对象的属性提供setter方法

public class Student {
    private Integer id;
    private String name;
    
    public void setId(Integer id) {this.id = id;}
    public void setName(String name) {this.name = name;}
}

在配置文件中通过set方式赋值

<!--通过setter方法注入依赖-->
    <bean id="student4" class="com.tulun.Spring.IOC.pojo.Student">
        <property name="id" value="12"/>
        <property name="name" value="Java31"/>
    </bean>

通过set方式使用的是property标签

注入的依赖也可以是自定义类型


    <!--注入自定义类型-->
    <bean id="user" class="com.tulun.Spring.IOC.pojo.User">
        <constructor-arg name="name" value="Java"/>
    </bean>
    <bean id="student5" class="com.tulun.Spring.IOC.pojo.Student">
        <property name="id" value="12"/>
        <property name="name" value="Java31"/>
        <!--value属性:将参数按照Syringe类型类解析  ref类型:Spring中管理的对象的Id值-->
        <property name="user" ref="user"/>
    </bean>

自定义类型也是要交给spring管理,如何获取管理对象实例呢
使用ref属性来获取值,该ref会自动识别为spring中对象的名字
使用value属性来获取值,spring会认为仅仅是一个字符串值

依赖也可以是集合类型

<!--注入集合类型-->
    <bean id="student6" class="com.tulun.Spring.IOC.pojo.Student">
        <!--注入list类型-->
        <property name="bookName" >
            <list>
                <value>语文</value>
                <value>数学</value>
                <value>英语</value>
            </list>
        </property>


        <!--注入map类型-->
        <property name="bookScore">
            <map>
                <entry key="语文" value="98.7"/>
                <entry key="数学" value="99"/>
            </map>
        </property>
    </bean>

基于注解形式注入依赖

@Value :注入普通类型属性
@Resource :注入对象类型
@Autowired :注入对象类型

@Value
该注解只能添加到普通类型上, @Value(“1”)注解中可以赋值完成对基础属性的依赖注入

@Component(value = "student")
public class Student {
    @Value("1")
    private Integer id;
}

@Resource
该注解是注入对象类型
是有Java 提供的,注意不是spring框架提供,默认按照类型来查找并注入类

@Component(value = "student")
public class Student {
    //自定义类型
   @Resource(name = "user")
    private User user;

@Autowired
注入对象类型 ,是Spring框架提供的,按照名称来注入

@Component(value = "student")
public class Student {
    //自定义类型
   @Autowired
    private User user;

版权声明:本文为xasasaa原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。