spring 的"零配置"支持

来源:互联网 发布:nginx 访问目录 403 编辑:程序博客网 时间:2024/06/06 06:30

“”零配置“支持只是说减少xml配置文件中配置的使用,而是通过注解的方式来搜索Bean类。

Spring提供了几个注释来标注Spring Bean

1 @Component: 标注一个普通的Spring Bean类

2 @Controller:  标注一个控制器组件类

3 @Service: 标注一个业务逻辑组件类

4 @Repository:标注一个DAO组件类


与xml搜索配置bean一样,代码没有多大修改,只需要在实现类中条件@Component.




bean.xml配置文修改为:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:p="http://www.springframework.org/schema/p"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-4.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.0.xsd">        <context:component-scan base-package="org.lizengjie.service"/></beans>

需要添加红色的包

最后运行程序为:



在默认情况下,spring会自动搜索所有以@Component,@Controller,@Service 和@Repository标注的java类,并将它们当成spring bean来处理。

除此之外,还可以通过为<component-scan>元素添加<include-fifter>或者<exclude-filter>子元素来指定spring bean类。只要位于指定路径下的java满足这种规则,即使这些java类没有使用任何Annotation标注,Spring一样会将他们当成bean类来处理。


<include-filter>元素用于指定满足该规则的java类会白当成bean类处理。

<exclude-fiflter>指定满足该规则的java类不会被当成Bean类处理。

使用这两个元素时都要求指定如下两个属性:

type:指定过滤器类型

expression:指定过滤器所需要的表达式


spring内键支持4种过滤器:

1 annotation 

2 assignable:类名过滤器

3 regex:正则表达式过滤器

4 aspectj:Aspectj过滤器


bean的作用域

使用@Resource 配置依赖

使用@PostConstruct和@PreDestroy


0 0