使用注解实现自动装配(Autowired和Resource)

使用注解实现自动装配(Autowired和Resource)

注解使用须知:

​ 1.导入约束: context约束

​ 2.配置注解的支持:context:annotation-config/ (重要!勿忘!)

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

       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd

        ">

@Autowired

直接在属性上使用即可! 也可以在set方式上使用 ! (不需要set方法也即可)

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

Autowired默认是按照类型注入,如果多个bean引用同一个实体类时,会报错,需要用@Qualifier按照指定id名进行注入

/*
@Autowired作用:注入属性,默认按照类型注入,如果多个类型有多个实现
则按照名称注入
(required = false):默认是true,false为默认启动的时候,不去直接注入这个属性(懒加载),使用的时候加载
值为true意为启动的时候必须完成这个注入
*/

<!--开启注解支持-->
    <context:annotation-config/>
    <bean id="cat1" class="com.liqiliang.pojo.Cat"/>
    <bean id="cat2" class="com.liqiliang.pojo.Cat"/>
    <bean id="dog1" class="com.liqiliang.pojo.Dog"/>
    <bean id="dog2" class="com.liqiliang.pojo.Dog"/>

    <bean id="person" class="com.liqiliang.pojo.Person"/>
@Autowired
    @Qualifier(value = "cat1")
    private Cat cat;

    @Autowired
    @Qualifier(value = "dog2")
    private Dog dog;
    private String name;

@Resource注解

    @Resource(name = "cat1")
    private Cat cat;

    @Resource(name = "dog2")
    private Dog dog;
    private String name;
<!--开启注解支持-->
    <context:annotation-config/>
    <bean id="cat1" class="com.liqiliang.pojo.Cat"/>
    <bean id="cat2" class="com.liqiliang.pojo.Cat"/>
    <bean id="dog1" class="com.liqiliang.pojo.Dog"/>
    <bean id="dog2" class="com.liqiliang.pojo.Dog"/>
    <bean id="person" class="com.liqiliang.pojo.Person"/>

@Resource和@Autowired的区别:

  • 都是使用自动装配的,都可以放在属性字段上
  • @Autowired 通过byType的方式实现
  • @Resource 默认通过byName的方式实现,如果找不到名字,再通过byType实现, 如果两个都找不到就报错

使用注解开发:
在spring4之后.要使用注解开发,必须要保证AOP包的导入
导入context的约束

    <!--指定要扫描的包,这个包下的注解就会生效-->
    <context:component-scan base-package="com.liqiliang.pojo"/>
package com.liqiliang.pojo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

// 等价于   <bean id="user" class="com.liqiliang.pojo.User"/>
@Component
public class User {
    // 相当于 <property name="name" value="小李"/>
    @Value("小李")
    private String name;

    public String getName() {
        return name;
    }
}

扩展:

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

 public Person(@Nullable String name) {
        this.name = name;
    }
posted @ 2020-05-13 15:36  阿亮在努力  阅读(283)  评论(0)    收藏  举报