前言
- 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配置文件来说,里面的内容大大的减少了,从而开发的效率提高了。