spring标签context:component-scan和context:annotation-config学习总结

1.  <context:annotation-config>学习总结

使用springBeanPostProcessor时,要先在spring容器中声明要使用BeanPostProcessor,比如要使用@Autowired注解就必要向spring容器中声明相BeanPostProcessor

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

以此类推使用其他的BeanPostProcessor也需要先向spring容器中声明。

Spring提供了<context:annotation-config>来简化配置。

该配置是隐式地向 Spring容器注册

AutowiredAnnotationBeanPostProcessor、

RequiredAnnotationBeanPostProcessor、

CommonAnnotationBeanPostProcessor

以及PersistenceAnnotationBeanPostProcessor这4个BeanPostProcessor。

2.  <context:component-scan>学习总结

使用Spring的都会知道怎样在spring容器中配置一个自己的bean,那就是使用<bean>标签

<bean id="dog" class="anno.demo01.pojo.Husky"></bean>

如果不想在spring的容器中配置一个一个的<bean>标签,那么就可以使用注解配置实现bean的自动载入。

<context:component-scan base-package="anno.demo01.pojo" />

该配置包含了<context:annotation-config>的配置,所以配置了<context:component-scan>就不用配置<context:annotation-config>

<context:component-scan>中需要指定一个包名base-package,如果在指定包名及其子包下的某个类上有@Component,@Repository,@Service,@Controller注解,就会将这个对象作为Bean注入进容器当中。

其中需要注意的是

@Component是所有受Spring管理件的通用形式;而@Repository@Service @Controller@Component化,用表示更具体的用例(@Repository对应持久化@Service对应服务@Controller对应现层)。也就是能用@Component注解件类,但如果用@Repository@Service @Controller注解它,你的类能更好地被工具处理,或与切面联。

<!--指定anno包及其子包下要扫描的注解-->

<context:component-scan base-package="anno">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
  </context:component-scan>
<!--指定anno包及其子包下不要扫描的注解-->

<context:component-scan base-package="anno">
    <!--指定要排除的注解-->
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
  </context:component-scan>

 ------------------------------------------------

原谅我的文章标题里不能输入"<>",会提示错误


如有错误,还请大侠及时指出,多谢!

 ------------------------------------------------


猜你喜欢

转载自blog.csdn.net/qq_36819098/article/details/80082916