码迷,mamicode.com
首页 > 编程语言 > 详细

Spring注解自动注入Bean

时间:2015-05-21 21:53:57      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

我们知道采用Spring注解时,配置如下:

[html] view plaincopy
 
  1. <context:annotation-config />  
  2.   
  3. <context:component-scan base-package="cn.itkt"></context:component-scan>  

这样的话,在com包及其所有子包下的所有类如果含有@Component、@Controller、@Service、@Repository等注解的话都会自动纳入到Spring容器中,但是每个类都一个个加上注解,有时难免觉得繁琐,其实Spring也为我们提供了自动为类加上注解的功能。配置如下:

[html] view plaincopy
 
  1. <context:component-scan base-package="cn.itkt" use-default-filters="false">  
  2.     <context:include-filter type="regex" expression="cn.itkt.*.service.*.*" />  
  3.     <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />  
  4. </context:component-scan>  

我们可以看到加了context:include-filter标签和context:exclude-filter标签。

context:include-filter

此标签的含义是:在其扫描到的所有类中,全部自动加上注解并纳入Spring容器中,比如有个类为

[java] view plaincopy
 
  1. public class StudentService implements IStudentService {  
  2. }  

那么该标签等用于为StudentService类加上@Component注解,且bean的id为studentService。

[java] view plaincopy
 
  1. @Component("studentService")  
  2. public class StudentService implements IStudentService {  
  3. }  

context:exclude-filter

此标签的含义是:排除扫描到的所有类,不纳入Spring容器中。

 

但需要注意的是,采用自动注入,类名不能相同(即便包名不同),因为自动注入时,id与类名相同,所以如果两个类名一样的话,会因为Bean的id相同而报错。

如果类名一定要相同的话,只能是其中一个类,手动加上注解并将名称改为其他。

Spring注解自动注入Bean

标签:

原文地址:http://www.cnblogs.com/duanxz/p/4520571.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!