Spring的@Component注解的使用

来源:互联网 发布:淘宝 饰品店 利润 编辑:程序博客网 时间:2024/04/28 10:10
ScanTest.java
package cn.xhx.spring.scan.test;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import cn.xhx.spring.scan.Person;public class ScanTest {/** * 原理 * 1、启动spring容器,sql容器解析配置文件 * 2、当解析到<context:component-scan base-package="cn.xhx.spring.scan"> * </context:component-scan> * 就会在上面指定的包及其子包中扫描所有类,看哪些类上面有@Component注解 * 3、如果有注解,则有如下规则 * @Component * public class PersonDaoImpl { *  * } * 等于 * <bean id="personDaoImpl" class="..."></bean> id的值:把类的第一个字母变成小写,其他字母不变 * ---------------------------------- * @Component("personDao") * public class PersonDaoImpl { *  * } * 等于 * <bean id="personDao" class="..."></bean> * 4、按照@Resource赋值 */@Testpublic void ScanTest() {ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");Person person = (Person)applicationContext.getBean("person");person.getStudent().say();//结果:"student say"}}
Person.java
package cn.xhx.spring.scan;import javax.annotation.Resource;import org.springframework.stereotype.Component;@Component("person")public class Person {@Resource(name="student")private Student student;public Student getStudent() {return student;}}
Student.java
package cn.xhx.spring.scan;import org.springframework.stereotype.Component;@Component("student")public class Student {public void say() {System.out.println("student say");}}
applicationContext.xml
<?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"><context:component-scan base-package="cn.xhx.spring.scan"></context:component-scan></beans>




0 0
原创粉丝点击