1、建包cn.google.annotation.scan 用于类扫描
2、导入 Student.java,Person.java,applicationContext-scan-annotation.xml
3、在 applicationContext-scan-annotation.xml 中
<?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">
<!--
类扫描的注解解析器
component 指的就是一个类
base-package 在该包及子包中进行扫描
-->
<context:component-scan base-package="cn.google.annotation.scan"></context:component-scan>
</beans>
4、在 Person.java 中:
@Component("a")
public class Person{
@Resource(name="b")
private Student student;
public void showStudent(){
this.students.show();
}
}
在 Student.java 中:
@Component("b")
public class Student{
public void show(){
s.o.p("student");
}
}
5、建测试类 ScanTest.java
public class ScanTest extends SpringInit{
@Test
public void testPerson(){
Person person = (Person)context.getBean("a");
person.showStudent();
}
}
结果:创建student对象,执行 showStudent() 方法。
类扫描的注解:
1、加入命名空间,同DI
2、注解解析器变成“类扫描”
<context:component-scan base-package="cn.google.annotation.scan"></context:component-scan>
·该注解解析器包含了两个功能:“依赖注入”和“类扫描”
·在 base-package 包以及子包下查找所有的类
3、如果一个类上加了 @Component 注解,就会进行如下的法则:value 属性匹配 <bean> 中的id值
如果其 value 属性的值为""
@Component
pulbic class Person(){} == <bean id="person" class="...Person">
如果其value 属性不为“”
@Component("p")
pulbic class Person(){} == <bean id="p" class="...Person">
4、执行 @Resource 法则
xml与注解:
1、xml 效率高但麻烦,
2、注解书写简单,但是效率低