Spring的@Component注解的使用

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赋值
	 */
	@Test
	public 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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值