《Spring》-----容器的注解

前言

  • Spring容器的注解帮助我们提升很大的工作效率,我们从此不用在去配置相关的bean。这些工作可以完全让Spring去管理甚至去创建。下面小编带着读者去解析Spring一些相关注解的原理。

1、依赖注入的注解

- @Resource注解:

  • 此注解严格来说是java的注解,并不是Spring开发的。要想了解此注解是怎么用的,请看下面的例子。
配置文件
        <?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 id="person" class="com.spring.di.annotation.Person"></bean>
           <bean id="student" class="com.spring.di.annotation.Student"></bean>  

           <!-- 启动依赖注入的注解解析器 -->
            <context:annotation-config></context:annotation-config>
person类
public class Person {
    @Resource(name="student")
    private Student student;
    public Student getStudent() {
        return student;
    }
}
student类
public class Student {
    public void say(){
        System.out.println("student");
    }
}

@Resource注解原理解析

当启动spring容器的时候,Spring会创建两个对象;当spring容器解析到 <context:annotation-config></context:annotation-config>的时候,spring容器会在spring容器管理的bean的范围内查找这些类的属性上面是否加了@Resource注解,如果某类加了@Resource注解,则spring会解析@Resource注解的name属性:
1、如果name属性为”“,spring容器会得到该注解所在的属性的名称和spring容器中的id做匹配,如果匹配成功,则赋值;如果匹配不成功,则按照类型进行匹配。
2、如果name属性的值不为”“, 则按照name属性的值和spring的id做匹配,如果匹配成功,则赋值,不成功,则报错。

@Autowired注解:

  • 按照类型匹配的注解,这是Spring开发的注解,比如,person的类型如下
    class="com.spring.di.annotation.Person"

@Qualifier注解:

  • 按照id进行匹配的注解。比如说`id=”person”

`

2、扫描类的注解

@Component注解:

  • 此注解将Spring容器中的bean当成一个组件,将扫描到带有@Component的类注入到Spring容器中。比如,配置文件的配置如下所示。
 <!-- 
        component:把一个类放入到spring容器中,该类就是一个component
        在base-package指定的包及子包下扫描所有的类
 --> 
 <context:component-scan basepackage="com.spring.scan">
 </context:component-scan>

Component注解原理解析

当spring容器启动后,spring容器解析到配置文件

<context:component-scan basepackage="com.spring.scan">
 </context:component-scan>

时,就会在上面指定的包及子包中扫描所有的类,看哪些类上面有@Component注解,如果有该注解,就会在Spring容器中自动创建该类的bean,比如说person类上面加了该注解,则Spring会这样创建bean:
<bean id="person" class"..."/> 其中id的值是把类的第一个字母变成小写,而其他字母不变。最后再按照@Resource注解的规则进行赋值,或者按照其它注解进行赋值。

小结

  • 其实这两种注解在程序执行的效率上都不如原始xml中已经写好的那些bean,因为这些注解都需要Spring进行扫描和赋值啊,但是对于Spring配置文件来说,里面的内容大大的减少了,从而开发的效率提高了。
评论 22
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值