Spring通过注解实现自动装配

1. 导入注解依赖并开启支持注解;

<?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/>

</beans>

2. 使用注解进行开发

public class People {
    @Autowired
    private Dog dog;
    @Autowired
    private Cat cat;
    private String name;
    private int age;

3. 注解Autowired的使用

我们可以使用@Autowired实现自动装配,它有很多种使用方式:

3.1 直接写在属性上

直接写在属性上是可以不要set方法的。

public class People {
    @Autowired
    private Dog dog;
    @Autowired
    private Cat cat;
    private String name;
    private int age;

3.2 写在set方法上(了解)

public class People {
    private Dog dog;
    private Cat cat;
    private String name;
    private int age;

    @Autowired
    public void setDog(Dog dog) {
        this.dog = dog;
    }

3.3 @Autowried结合@Qualifer使用

当我们在开放中,需要在Spring容器中装配多个同一类型的对象时,可以使用@Autowried结合@Qualifer一起使用

public class People {
    @Autowired
    @Qualifier(value = "dog2")
    private Dog dog;

4. 使用@Resource实现自动装配

@Resource是jdk自带的注解,他比@Autowried更强大,但不咋用。

使用@Resource自动装配也是可以不用set方法的。

public class People {
    @Resource
    private Dog dog;
    @Resource(name = "cat2")
    private Cat cat;
    private String name;
    private int age;

5. @Autowried和@Resource的区别

都可以实现自动装配的功能;

Autowried是Spring框架的注解,Resource是JDK自带的注解;

Autowried默认采用的是byType的方式实现的自动装配,当存在多个同一类型的bean时,需要结合Qualifer实现自动装配;

Resource默认采用的是byName的方式实现的自动装配,当根据名称匹配不到bean的id时,会自动切换到byType进行匹配,当存在多个同一类型的bean时,可以根据Resource中设置的name的值进行匹配。

posted @ 2020-05-08 20:32  老王同鞋  阅读(642)  评论(0编辑  收藏  举报