mvc:annotation-driven与context:component-scan及context:annotation-config的区别

mvc:annotation-driven/context:component-scan/的区别
context:component-scan/标签是告诉Spring 来扫描指定包下的类,并注册被@Component,@Controller,@Service,@Repository等注解标记的组件。
mvc:annotation-driven/是告知Spring,我们启用注解驱动。然后Spring会自动为我们注册上面说到的几个Bean到工厂中,来处理我们的请求。
mvc:annotation-driven/context:annotation-config/的区别
当我们需要使用注解模式时,直接在Spring配置文件中定义这些Bean显得比较笨拙,例如:
使用@Autowired注解,必须事先在Spring容器中声明AutowiredAnnotationBeanPostProcessor的Bean:

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor "/>

使用 @Required注解,就必须声明RequiredAnnotationBeanPostProcessor的Bean:

 <bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>

简单的说,用什么注解,就需要声明对应的BeanPostProcessor。这样的声明未免太不优雅,而Spring为我们提供了一种极为方便注册这些BeanPostProcessor的方式,即使用<context:annotation- config/>隐式地向 Spring容器注册AutowiredAnnotationBeanPostProcessor、RequiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor以及PersistenceAnnotationBeanPostProcessor这4个BeanPostProcessor。

另外,在我们使用注解时一般都会配置扫描包路径选项,即context:component-scan/。该配置项其实也包含了自动注入上述processor的功能,因此当使用context:component-scan/后,即可将context:annotation-config/省去,但必须要配置全!以防万一,还是同时声明的好。
补充一个Spring配置项之<aop:aspectj-autoproxy />作用
通过配置织入@Aspectj切面
虽然可以通过编程的方式织入切面,但是一般情况下,我们还是使用spring的配置自动完成创建代理织入切面的工作。
通过aop命名空间的<aop:aspectj-autoproxy
/>声明自动为spring容器中那些配置@aspectJ切面的bean创建代理,织入切面。当然,spring
在内部依旧采用AnnotationAwareAspectJAutoProxyCreator进行自动代理的创建工作,但具体实现的细节已经被<aop:aspectj-autoproxy
/>隐藏起来了 <aop:aspectj-autoproxy
/>有一个proxy-target-class属性,默认为false,表示使用jdk动态代理织入增强,当配为<aop:aspectj-autoproxy
poxy-target-class=“true”/>时,表示使用CGLib动态代理技术织入增强。不过即使proxy-target-class设置为false,如果目标类没有声明接口,则spring将自动使用CGLib动态代理。

posted @ 2020-01-09 10:41  thinkworld  阅读(382)  评论(0编辑  收藏  举报