最小化Spring XML配置
对于比较大的项目来说,使用<bean>元素定义Bean以及使用<constructor-arg>或<property>元素装配Bean会使得Spring的XML配置文件越来越复杂,但Spring提供了几种技巧,可以减少XML的配置数量。
1、自动装配(autowiring)
有助于减少甚至消除配置<property>元素和<constructor-arg>元素,让Spring自动识别如何装配Bean的依赖关系。
2、自动检测
3.2 使用注解装配
Spring容器默认禁用注解装配,需要在Spring配置中启用它,最简单的启用方式时使用Spring的context命名空间配置中的<context:annotation-config>元素。
<?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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
</beans>
Spring支持的三种用于自动装配的注解:
1、Spring自带的@Autowired注解
2、JSR-330的@Inject注解
3、JSR-250的@Resource注解
有关Spring注解的部分,感觉书上讲的不是特别好,找了一篇讲的比较好的博客学习:
Spring5:@Autowired注解、@Resource注解和@Service注解
3.3 自动检测Bean:
在前面的使用注解注入Bean时,虽然不用手动注入Property,但还是需要在XML中声明各个Bean。为了解决这个问题,让XML中不再出现与java代码有关的配置,可以使用<conxtext:component-scan>元素。它除了完成与<conxtext:annotation-config>一样的工作,还允许Spring自动检测Bean和定义Bean,即不再需要<Bean>元素,Spring中的Bean基本上都可实现定义和装配。
为了配置Spring自动检测,需要使用<conxtext:component-scan>代替<conxtext:annotation-config>:
<context-component-scan
base-package="com.springinaction.springidol">
</context-component-scan>
在使用这种方式时,为了使之知道那些类需要注册为Java Bean,需要为自动检测标注Bean:
默认情况下,<conxtext:component-scan>查找使用构造型注解所标注的类,这些特殊的注解如下:
1、@Component-通用的构造型注解,标识该类为Spring组件
2、Controller-标识将该类定义为Spring MVC controller
3、Respository-标识将该类定义为数据仓库
4、Service-标识将该类定义为服务
5、使用Component标注的任意自定义注解
3.3.2 过滤组件扫描
<context-component-scan
base-package="com.springinaction.springidol">
<context:include-filter type="assignable" expression="com.springinaction.springidol.Instrument" />
</context-component-scan>
过滤器类型:
过滤器类型 | 描述 |
annotation | 过滤器扫描使用指定注解标注的那些类。通过expression属性指定要扫描的注解 |
assignable | 过滤器扫描派生于expression属性所指定类型的那些类 |
aspectj | 过滤扫描器与expression属性所指定的AspectJ表达式所匹配的那些类 |
custom | 使用自定义的org.springframework.core.type.TypeFilter实现类,该类由expression属性指定 |
regex | 过滤器扫描类的名称与expression属性所指定的正则表达式所匹配的那些类 |