如果每一个自建类都使用 <bean> 创建 bean 对象,我们就需要书写大量的代码;如果工程量较大时,则会显得代码多而乱;而 context:component-scan标签 的扫描式创建 bean 对象会更高效而简洁。
Sprng容器通过 context:component-scan标签 扫描其 base-package标签 属性值指定的包及其子包内的所有的类并实例化被@Component、@Repository、@Service或@Controller 等注解所修饰的所有的类。
@Component:基本注解
@Respository:持久层(一般为dao层)注解
@Service:服务层或业务层(一般为service层)注解
@Controller:控制层(一般为controller层)注解
默认情况下Spring依据默认命名策略为通过注解实例化的对象命名:类名第一个字母小写. 也可以在注解中通过@Component、@Repository、@Service或@Controller 注解的 value属性 标识名称。
package com.jd.vo;
import org.springframework.stereotype.Repository;
@Repository
public class Student {
public Student() {
System.out.println("我是一名学生");
}
}
package com.jd.vo;
import org.springframework.stereotype.Component;
@Component
public class School {
public School() {
System.out.println("这是一所学校");
}
}
创建两个类,分别使用 @Repository 和 @Component 标识;
application.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"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
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-4.3.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">
<context:component-scan base-package="com.jd.vo"></context:component-scan>
</beans>
在 application.xml 中使用 context:component-scan标签 将这两个类都实例化;
package com.jd.test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.jd.vo.Student;
public class Test {
public static void main(String[] args)
{
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml");
}
}
运行 Test.java 我们会看到控制台的提示信息:
刚好是我们的构造方法中的输出语句。
注意:
1、使用 context:component-scan标签 需要添加spring-aop-4.3.10.RELEASE.jar包
2、base-package标签属性属性值:
a、Spring 容器将会扫描该属性值指定包及其子包中的所有类;
b、该属性值支持*通配符,例如“com.lq.*.imp”表示扫描诸如com.lq.book.imp包及其子包中的类;
c、当需要扫描多个包时, 使用逗号分隔;
d、resource-pattern标签属性可以指定Spring容器仅扫描特定的类而非基包下的所有类,比如resource-pattern="/*.class"表示只扫描基包下的类,基包的子包不会被扫描。