Spring注解自动注入Bean
2015-05-21 19:01
573 查看
我们知道采用Spring注解时,配置如下:
[html] view plaincopy
<context:annotation-config />
<context:component-scan base-package="cn.itkt"></context:component-scan>
这样的话,在com包及其所有子包下的所有类如果含有@Component、@Controller、@Service、@Repository等注解的话都会自动纳入到Spring容器中,但是每个类都一个个加上注解,有时难免觉得繁琐,其实Spring也为我们提供了自动为类加上注解的功能。配置如下:
[html] view plaincopy
<context:component-scan base-package="cn.itkt" use-default-filters="false">
<context:include-filter type="regex" expression="cn.itkt.*.service.*.*" />
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
我们可以看到加了context:include-filter标签和context:exclude-filter标签。
context:include-filter
此标签的含义是:在其扫描到的所有类中,全部自动加上注解并纳入Spring容器中,比如有个类为
[java] view plaincopy
public class StudentService implements IStudentService {
}
那么该标签等用于为StudentService类加上@Component注解,且bean的id为studentService。
[java] view plaincopy
@Component("studentService")
public class StudentService implements IStudentService {
}
context:exclude-filter
此标签的含义是:排除扫描到的所有类,不纳入Spring容器中。
但需要注意的是,采用自动注入,类名不能相同(即便包名不同),因为自动注入时,id与类名相同,所以如果两个类名一样的话,会因为Bean的id相同而报错。
如果类名一定要相同的话,只能是其中一个类,手动加上注解并将名称改为其他。
[html] view plaincopy
<context:annotation-config />
<context:component-scan base-package="cn.itkt"></context:component-scan>
这样的话,在com包及其所有子包下的所有类如果含有@Component、@Controller、@Service、@Repository等注解的话都会自动纳入到Spring容器中,但是每个类都一个个加上注解,有时难免觉得繁琐,其实Spring也为我们提供了自动为类加上注解的功能。配置如下:
[html] view plaincopy
<context:component-scan base-package="cn.itkt" use-default-filters="false">
<context:include-filter type="regex" expression="cn.itkt.*.service.*.*" />
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
我们可以看到加了context:include-filter标签和context:exclude-filter标签。
context:include-filter
此标签的含义是:在其扫描到的所有类中,全部自动加上注解并纳入Spring容器中,比如有个类为
[java] view plaincopy
public class StudentService implements IStudentService {
}
那么该标签等用于为StudentService类加上@Component注解,且bean的id为studentService。
[java] view plaincopy
@Component("studentService")
public class StudentService implements IStudentService {
}
context:exclude-filter
此标签的含义是:排除扫描到的所有类,不纳入Spring容器中。
但需要注意的是,采用自动注入,类名不能相同(即便包名不同),因为自动注入时,id与类名相同,所以如果两个类名一样的话,会因为Bean的id相同而报错。
如果类名一定要相同的话,只能是其中一个类,手动加上注解并将名称改为其他。
相关文章推荐
- spring注解自动注入bean
- Spring注解自动注入Bean
- Spring 注解Autowired自动注入bean异常解决
- 类注解Spring注解自动注入Bean
- Spring注解自动注入Bean
- hessian与spring的完美结合(使用spring注解自动注入bean)
- SSH下使用Spring注解自动注入bean
- Spring注解自动注入Bean
- Spring4.0MVC学习资料,注解自动扫描bean,自动注入bean(二)
- SSH下使用Spring注解自动注入bean
- 框架 day36 Spring3 入门,DI依赖注入,装配bean基于xml/注解, 整合Junit4,配置约束自动提示
- 用spring的注解建立bean与bean之间的关系组件装配及自动注入依赖对象
- spring-使用注解实现Bean自动装配1
- 关于非Spring管理下的Bean通过反射在newInstance()下的自动注入问题
- 解决Spring+Quartz无法自动注入bean问题
- Spring注解-@Configuration注解、@Bean注解以及配置自动扫描、bean作用域
- Spring基础 注解实现Bean依赖注入
- Spring常用注解,自动扫描装配Bean
- Spring(三、Spring Bean自动装配和注解注入)
- Spring常用注解,自动扫描bean