spring中context:component-scan标签

Spirng容器通过context:component-scan标签扫描其base-package标签属性值指定的包及其子包内的所有的类并实例化被@Component、@Repository、@Service或@Controller等注解所修饰的类。

@Component:基本注解
@Respository:持久层(一般为dao层)注解
@Service:服务层或业务层(一般为service层)注解
@Controller:控制层(一般为controller层)注解

默认情况下Spring依据默认命名策略为通过注解实例化的对象命名:类名第一个字母小写. 也可以在注解中通过@Component、@Repository、@Service或@Controller 注解的value属性标识名称。

要使用这个标签,首先要引包:spring-aop-4.3.10.RELEASE.jar(自行百度,或看我的博客:初识Spring中有提到)

以一个Student类来举例:

@Component
public class Student{
	private Date now;
	
	public void setNow(Date now){
		this.now=now;
	}
	public Date getNow(){
		return now;
	}
}

在xml文件中先在Namespaces中将context选项勾上,然后如下:

	<bean class="java.util.Date"></bean>
	<!--base-package的值为要扫描的包,则这个包中,所有带有所需注解的类都会被实例化-->
	<context:component-scan base-package="com.jd"></context:component-scan>
	

我们再写个Test类测试一下:

public class Test{	
	public static void main(String[] args){
		ClassPathXmlApplicationContext classPathXmlApplictionContext = new ClassPathXmlApplicationContext("application.xml");
		Student student = classPathXmlApplicationContext.getBean(Student.class);
		System.out.println(student.getNow());
	}
}

base-package标签属性属性值:
a、Spring 容器将会扫描该属性值指定包及其子包中的所有类;
b、该属性值支持通配符,例如“com.lq..imp”表示扫描诸如com.lq.book.imp包及其子包中的类;
c、当需要扫描多个包时, 使用逗号分隔;
d、resource-pattern标签属性可以指定Spring容器仅扫描特定的类而非基包下的所有类,比如resource-pattern="/*.class"表示只扫描基包下的类,基包的子包不会被扫描。

context:component-scan子标签:
1、<context:include-filter> 子标签设定Spring容器扫描时仅扫描哪些expression指定的类,该子标签需要和context:component-scan父标签中的use-default-filters属性一起使用;
2、<context:exclude-filter> 子标签设定Spring容器扫描时不扫描哪些expression指定的类;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值