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元素时,隐式地包含了AutowiredAnnotationBeanPostProcessor和CommonAnnotationBeanPostProcessor。这意味着这两个组件是自动检测并连接在一起的 - 所有这些都没有在XML中提供任何bean配置元数据。
您可以通过包含值为false的annotation-config属性来禁用AutowiredAnnotationBeanPostProcessor和CommonAnnotationBeanPostProcessor的注册。