public class Student { public void say() { System.out.println("student say"); } }
public class Person { //@Resource(name="student") @Resource() private Student student; public void say(){ this.student.say(); } }
<?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" xmlns:tx="http://www.springframework.org/schema/tx" 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 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <bean id="student" class="com.sn.domain.Student"></bean> <bean id="person" class="com.sn.domain.Person"></bean> <context:annotation-config></context:annotation-config> </beans>
/** * 原理: * 1、启动spring容器 * 2、把person和student两个bean实例化 * 3、当spring容器解析到 * <context:annotation-config></context:annotation-config> * 就会启动依赖注入的注解解析器 * 4、spring容器会在纳入spring管理的bean的范围内查找,看这些类的哪些属性上加有@Resource注解 * 5、如果某一个属性上加有@Resource注解 * 会查看该注解的name属性的值是否为"" * 如果为"",则会把该注解所在的属性的名称和spring容器中的id的值作匹配,如果匹配成功,则赋值 * 如果匹配不成功,则按照类型进行匹配,匹配成功则赋值 * 如果再匹配不成功,则报错 * 如果不为"",则把该注解的name属性的值和spring容器中id的值作匹配,如果匹配成功,则赋值 * 如果匹配不成功,则直接报错 * 说明: 注解只能作用于引用类型 xml与注解的对比 xml的效率比较高,书写比较麻烦 注解的书写比较简单,效率比较低 * @author zd * */ public class AnnotationTest { @Test public void testAnnotation(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); Person person = (Person)context.getBean("person"); person.say(); } }
时间: 2024-11-08 07:29:12