@Component public class Student { public void say() { System.out.println("student say"); } }
@Component 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"> <context:component-scan base-package="com.sn.domain"></context:component-scan> </beans>
/** * 原理 * 1、启动spring容器 * 2、spring容器解析 * <context:component-scan base-package="com.itheima10.spring.scan"> </context:component-scan> 3、在base-package指定的包及子包中扫描,看哪些类上面是否含有@Component注解 4、如果有该注解 @Component public class Person { } == <bean id="person" class="..Person"> @Component("aa") public class Person { } == <bean id="aa" class="..Person"> 5、按照@Resource的解析步骤执行 说明: 整个过程扫描两次,效率越来越低,书写越来越简单 * @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-06 23:26:51