zoukankan      html  css  js  c++  java
  • Spring框架参考手册(4.2.6版本)翻译——第三部分 核心技术 6.10.3 自动检测类和注册bean的定义

    6.1.1 自动检测类和注册bean的定义

    Spring可以自动检测构造型类,并使用ApplicationContext注册相应的BeanDefinition。例如,以下两个类符合这种自动检测的条件:

    @Service
    public class SimpleMovieLister {
    
        private MovieFinder movieFinder;
    
        @Autowired
        public SimpleMovieLister(MovieFinder movieFinder) {
            this.movieFinder = movieFinder;
        }
    
    }
    @Repository
    public class JpaMovieFinder implements MovieFinder {
        // implementation elided for clarity
    }

    要自动检测这些类并注册相应的bean,需要将@ComponentScan添加到你的@Configuration类,其中basePackages属性是两个类的公共父包。 (或者,您可以指定包含每个类的父包的逗号/分号/空格分隔列表。)

    @Configuration
    @ComponentScan(basePackages = "org.example")
    public class AppConfig  {
        ...
    }

    为简洁起见,上面可能使用了注value属性,即ComponentScan(“org.example”)

    以下是另一种方法,通过使用XML

    <?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.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">
    
        <context:component-scan base-package="org.example"/>
    </beans>

    使用<context:component-scan>隐式启用<context:annotation-config>的功能。 使用<context:component-scan>时,通常不需要包含<context:annotation-config>元素。

    扫描类路径包要求在类路径中存在相应的目录条目。使用Ant构建JAR时,请确保不要激活JAR任务的files-only开关。此外,基于安全策略在某些环境中,类路径目录可能不会暴露,例如:JDK 1.7.0_45及更高版本上的独立应用程序(需要在清单中设置“Trusted-Library”;请参阅http://stackoverflow.com/questions/19394570/java-jre-7u45-breaks-classloader-getresources)。

    此外,使用component-scan元素时,隐式包含了AutowiredAnnotationBeanPostProcessorCommonAnnotationBeanPostProcessor。这意味着这两个组件是自动检测并连接在一起的 - 所有这些都没有在XML中提供任何bean配置元数据。

    您可以通过包含值为falseannotation-config属性来禁用AutowiredAnnotationBeanPostProcessorCommonAnnotationBeanPostProcessor的注册。

  • 相关阅读:
    100到简单加减乘除算法的程序
    安卓日程管理系统中的bug
    绑定到Collection与绑定到CollectionViewSource的不同及解决方案
    【WPF】完美的布局不留白——解决WrapPanel右侧留白问题
    WPF里最简单的控件的Style你能写对么?(默认Style是有问题的)
    WPF Bug清单之(13)——应该出现却没有出现的ListView水平滚动条
    [WPF Bug清单]之(12)——与自定义Attached Property相关的Binding Path运行时错误
    请争取你可以拥有的——即使你不在乎
    C#编码风格——using语句的位置
    【WPF】实现QQ中的分组面板(2)——添加动画
  • 原文地址:https://www.cnblogs.com/springmorning/p/10446242.html
Copyright © 2011-2022 走看看