Spring容器的依赖注入注解

1、bean

package DI_Annotation;

import DI_Setting.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import javax.annotation.Resource;
import javax.lang.model.element.Name;

/**
 * Created by Administrator on 2019/6/1.
 */
public class Person {
    @Resource(name = "student")
//    @Autowired 按照类型匹配
//    @Qualifier("student") 按照name匹配
    private Student student;

    public Student getStudent() {
        return student;
    }
}

2、bean

package DI_Setting;

import org.springframework.stereotype.Component;

/**
 * Created by Administrator on 2019/5/29.
 */
public class Student {
    public void say() {
        System.out.println("你好学生!");
    }
}

3、ApplicationContext.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
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd">
    <bean name="person" class="DI_Annotation.Person"></bean>
    <bean name="student" class="DI_Setting.Student"></bean>

    <!--启动依赖注入的注解解析器-->
    <context:annotation-config></context:annotation-config>
</beans>

4、单元测试

package DI_Annotation;

import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AnnotationTest {
    @Test
    public void testAnnotation() {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("DI_Annotation/DI_Annotation.xml");
        Person person = (Person) context.getBean("person");
        person.getStudent().say();
    }
}

5、输出
你好学生
6、解释说明
/**

  • 原理
  • 1、当启动Spring容器的时候,创建两个对象
  • 2、当Spring容器解析到
  • context:annotation-config</context:annotation-config>
    Spring容器会在Spring容器管理的bean的范围内查找这些类的属性上面是否加了 @Resource注解
    3、Spring解析 @Resource注解的name属性
    如果name值为“”
    说明该注解根本没有写name属性
    Spring容器会得到该注解所在的属性的名称和Spring容器中的id进行匹配,如果匹配成功,进行赋值
    如果匹配不成功,则按照类型进行赋值
    如果name属性的值不为“”
    则按照name的值,和Spring的ID匹配,如果匹配成功,则赋值,不成功,则报错
    4/!!!注解只适用于 引用类型!!!!!!!!!
    注解写法简单,但是效率比较低
    xml写法复杂,但是效率比较高
    */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值