在过去,我们经常使用setter来给属性赋值,这样会造成要写很多代码,如果属性一多,代码量就非常的惊人,虽然说不用我们自己写setter,但是代码量还是要算的。
那么,为了解决这个问题,spring就引入了注解来为Di中的属性赋值。
我们拿代码来说话
public class Person implements Serializable {
//基本类型
private Long pid;
//String
private String pname;
//引用类型
//引入注解,name在这里指的是配置文件中bean的id
@Resource(name="student_annotation")
private Student student;
//集合
private List list;
private Set set;
private Map map;
public void showStudent(){
this.student.show();
}
}
public class Student implements Serializable {
public void show(){
System.out.println("student");
}
}
配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">
<context:annotation-config></context:annotation-config>
<bean id="person_annotation" class="cn.ansel.annotation.Person"></bean>
<bean id="student_annotation" class="cn.ansel.annotation.Student"></bean>
</beans>
细心的人会发现,配置文件多了几行数据,没错
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
是它的命名空间及地址
又因为我们使用了注解,所以要加上注解解析器,否则注解不起作用
<!--
引入注解解析器
-->
<context:annotation-config></context:annotation-config>
测试
类
public class annotationTest {
@Test
public void test(){
//启动spring容器
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
//得到对象
Person person=(Person) applicationContext.getBean("person_annotation");
//调用方法
person.showStudent();
}
}
运行:
成功输出student.
1、 启动spring容器
2、 spring容器内部创建了两个对象person和student
3、 当spring容器解析到
启动依赖注入的注解解析器:
4、 spring容器在容器中查找所有的bean(prerson,student)
5、 看哪些bean的属性上面是否有Resource注解
6、 如果属性上面有该注解,再次检查是否有name属性
7、 如果没有name属性,则会把该注解标注的属性的名称获取到和spring容器中的id做匹配,如果匹配成功,则赋值,如果匹配不成功,则按照类型进行匹配,如果匹配成功,则赋值,如果匹配不成功,则报错。
8、 如果有name属性,则把name属性的值解析出来和spring容器中的id做匹配,如果匹配成功,则赋值,如果匹配不成功,则报错。
9、 从上述的步骤可以看出注解的效率比较低,xml的效率比较高,注解书写比较简单,xml书写比较复杂。
注意:
由于这里的@Resource是javax.annotation.Resource 包(扩展包),这时候spring不服,于是推出了自己的注解:
@Autowired
@Qualifier(“student_annotation”)`,因为qualifier里面有一个属性value,所以前面直接把它的值写上去。这两个注解加起来的作用跟@Resource的作用是一样的。
这个注解的作用是按照与引用类相同的类型与配置文件进行匹配。然后还有一个
Spring容器的关于di的注解
按照类型匹配
按照ID匹配
注解只能应用与引用类型