spring 自动装配注解

190 阅读2分钟

自动装配xml配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">
    <context:annotation-config></context:annotation-config>
    <!--    byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanId-->
    <!--    byName:会自动在容器上下文中查找,和自己对象属性类型相同的beanId-->
</beans>

@Autowired

直接在属性上使用即可!也可以在set方法上使用!

使用Autowired 我们可以不编写set方法了,前提是你这个自动装配的属性在IOC(Spring)容器中存在,且符合名字byname或类型bytype(type唯一)

科普:

@Nullableke

字段标记了这个注解,说明这个字段可以为null

@Autowired(required = false)

如果显式的定义了Autowired的required属性为false,说明这个对象可以为null,否则不允许为空

示例

package org.example.pojo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;

public class Person {
    //如果显式的定义了Autowired的required属性为false,说明这个对象可以为null,否则不允许为空
    @Autowired(required = false)
    private Cat cat;
    @Autowired
    private Dog dog;
    private String name;

    public Person(@Nullable String name) {
        this.name = name;
    }

    public Cat getCat() {
        return cat;
    }

    public Dog getDog() {
        return dog;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "cat=" + cat +
                ", dog=" + dog +
                ", name='" + name + '\'' +
                '}';
    }
}

@Qualifier

如果@Autowired自动装配的环境比较复杂即通过名字或类型都无法正确匹配到对应的bean, 那么可以通过@Qualifier显式的指定beanId配合@Autowired使用。

package org.example.pojo;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Autowired;

public class Person {
    @Autowired
    private Cat cat;
    @Autowired
    @Qualifier(value="beadId")
    private Dog dog;
    private String name;

    public Person(@Nullable String name) {
        this.name = name;
    }

    public Cat getCat() {
        return cat;
    }

    public Dog getDog() {
        return dog;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "cat=" + cat +
                ", dog=" + dog +
                ", name='" + name + '\'' +
                '}';
    }
}

@Resource

直接在属性上使用,前提是自动装配的属性在IOC(Spring)容器中存在,且符合名字byname或类型bytype(type唯一)

@Resource(name = "beanId")

若自动装配的属性不符合名字byname可以通过注解的name属性指定bean

@Resource 和@Autowired的异同

  • 都是用来自动装配的,都可以放在属性字段上
  • 都可以通过byname和bytype的方式显示
  • 在byname与bytype都找不到或type不唯一的情况下都会报错

*执行顺序不同:@Autowired默认通过bytype方式实现,@Resource默认通过byname方式实现