`

Spring 自动扫描组件或Bean

 
阅读更多

一、      Spring Auto Scanning Components —— 自动扫描组件

通常你可以在xml配置文件中,声明一个bean或者component,然后Spring容器会检查和注册你的bean或component。实际上,Spring支持自动扫描bean或component,你可以不必再在xml文件中繁琐的声明bean,Spring会自动扫描、检查你指定包的bean或component。

以下列举一个简单的Spring Project,包含了Customer、Service、DAO层,让我们来看一下手动配置和自动扫描的不同。

1.      Declares Components Manually——手动配置component

先看一下正常手动配置一个bean

DAO层,CustomerDAO.java如下:

复制代码
package com.lei.customer.dao;
 
public class CustomerDAO 
{
    @Override
    public String toString() {
        return "Hello , This is CustomerDAO";
    }    
}
复制代码

 Service层,CustomerService.java如下:

复制代码
package com.lei.customer.services;
 
import com.lei.customer.dao.CustomerDAO;
 
public class CustomerService 
{
    CustomerDAO customerDAO;
 
    public void setCustomerDAO(CustomerDAO customerDAO) {
        this.customerDAO = customerDAO;
    }
 
    @Override
    public String toString() {
        return "CustomerService [customerDAO=" + customerDAO + "]";
    }
 
}
复制代码

 

 

配置文件,Spring-Customer.xml文件如下:

复制代码
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
    <bean id="customerService" class="com.lei.customer.services.CustomerService">
        <property name="customerDAO" ref="customerDAO" />
    </bean>
 
    <bean id="customerDAO" class="com.lei.customer.dao.CustomerDAO" />
 
</beans>
复制代码

 

运行如下代码,App.java如下:

复制代码
package com.lei.common;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
import com.lei.customer.services.CustomerService;
 
public class App 
{
    public static void main( String[] args )
    {
        ApplicationContext context = 
          new ClassPathXmlApplicationContext(new String[] {"Spring-Customer.xml"});
 
        CustomerService cust = (CustomerService)context.getBean("customerService");
        System.out.println(cust);
 
    }
}
复制代码

 

输出结果:CustomerService [customerDAO=Hello , This is CustomerDAO]

 

2.      Auto Components Scanning——自动扫描组件

现在,看一下怎样运用Spring的自动扫描。

用注释@Component来表示这个Class是一个自动扫描组件。

Customer.java如下:

复制代码
package com.lei.customer.dao;
 
import org.springframework.stereotype.Component;
 
@Component
public class CustomerDAO 
{
    @Override
    public String toString() {
        return "Hello , This is CustomerDAO";
    }    
}
复制代码

 

CustomerService.java如下:

复制代码
package com.lei.customer.services;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
import com.lei.customer.dao.CustomerDAO;
 
@Component
public class CustomerService 
{
    @Autowired
    CustomerDAO customerDAO;
 
    @Override
    public String toString() {
        return "CustomerService [customerDAO=" + customerDAO + "]";
    }
}
复制代码

 

 

配置文件Spring-customer.xml如下

 

复制代码
<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-2.5.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-2.5.xsd">
 
    <context:component-scan base-package="com.lei.customer" />
 
</beans>
复制代码

 

 

 

注意:

以上xml文件中,加入了“context:component-scan”标签,这样就将Spring的自动扫描特性引入,base-package表示你的组件的存放位置,Spring将扫描对应文件夹下的bean(用@Component注释过的),将这些bean注册到容器中。

       最后运行结果与手动配置的结果一致。

3.      Custom auto scan component name——自定义扫描组件名称

上例中,默认情况下,Spring将把组件Class的第一个字母变成小写,来作为自动扫描组件的名称,例如将“CustomerService”转变为“customerservice”,你可以用“customerService”这个名字调用组件,如下:

CustomerService cust = (CustomerService)context.getBean("customerService");

 

你可以像下边这样,创建自定义的组件名称:

 

@Service("AAA")
public class CustomerService 
...

 

现在,可以调用自己定义的组件了,如下:

CustomerService cust = (CustomerService)context.getBean("AAA");

 

4.      Auto Components Scan Antotation Types——自动扫描组件的注释类型

有4种注释类型,分别是:

@Component      ——表示一个自动扫描component

@Repository              ——表示持久化层的DAO component

@Service             ——表示业务逻辑层的Service component

@Controller        ——表示表示层的Controller component

 

以上4种,在应用时,我们应该用哪一种?让我们先看一下@Repository、@Service、@Controller的源代码

复制代码
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {
 
    String value() default "";
 
}
复制代码

 

你还可以看一下@Service、@Controller的源代码,发现它们都用@Component注释过了,所以,在项目中,我们可以将所有自动扫描组件都用@Component注释,Spring将会扫描所有用@Component注释过得组件。

       实际上,@Repository、@Service、@Controller三种注释是为了加强代码的阅读性而创造的,你可以在不同的应用层中,用不同的注释,就像下边这样。

DAO层:

复制代码
package com.lei.customer.dao;
 
import org.springframework.stereotype.Repository;
 
@Repository
public class CustomerDAO 
{
    @Override
    public String toString() {
        return "Hello , This is CustomerDAO";
    }    
}
复制代码

 

 

Service层:

复制代码
package com.lei.customer.services;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import com.lei.customer.dao.CustomerDAO;
 
@Service
public class CustomerService 
{
    @Autowired
    CustomerDAO customerDAO;
 
    @Override
    public String toString() {
        return "CustomerService [customerDAO=" + customerDAO + "]";
    }
 
}
复制代码

 

 

二、      Spring Filter Components In Auto Scanning —— 在自动扫描中过滤组件

1.      Filter Component——include

下例演示了用“filter”自动扫描注册组件,这些组件只要匹配定义的“regex”的命名规则,Clasee前就不需要用@Component进行注释。

DAO层,CustomerDAO.java如下:

复制代码
package com.lei.customer.dao;
 
public class CustomerDAO 
{
    @Override
    public String toString() {
        return "Hello , This is CustomerDAO";
    }    
}
复制代码

 

Service层,CustomerService.java如下:

复制代码
package com.lei.customer.services;
 
import org.springframework.beans.factory.annotation.Autowired;
import com.lei.customer.dao.CustomerDAO;
 
public class CustomerService 
{
    @Autowired
    CustomerDAO customerDAO;
 
    @Override
    public String toString() {
        return "CustomerService [customerDAO=" + customerDAO + "]";
    }
 
}
复制代码

 

Spring Filtering,xml配置如下:

复制代码
<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-2.5.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-2.5.xsd">
 
    <context:component-scan base-package="com.lei" >
 
        <context:include-filter type="regex" 
                       expression="com.lei.customer.dao.*DAO.*" />
 
        <context:include-filter type="regex" 
                       expression="com.lei.customer.services.*Service.*" />
 
    </context:component-scan>
 
</beans>
复制代码

 

注意:

以上xml文件中,所有文件名字,只要包含DAO和Service(*DAO.*,*Service.*)关键字的,都将被检查注册到Spring容器中。

 

运行以下代码:

复制代码
package com.lei.common;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
import com.lei.customer.services.CustomerService;
 
public class App 
{
    public static void main( String[] args )
    {
        ApplicationContext context = 
        new ClassPathXmlApplicationContext(new String[] {"Spring-AutoScan.xml"});
 
        CustomerService cust = (CustomerService)context.getBean("customerService");
        System.out.println(cust);
 
    }
}
复制代码

 

运行结果:CustomerService [customerDAO=Hello , This is CustomerDAO]

 

2.      Filter Component——exclude

你也可以用exclude,制定组件避免被Spring发现并被注册到容器中。

以下配置排除用@Service注释过的组件

<context:component-scan base-package="com.lei.customer" >
        <context:exclude-filter type="annotation" 
            expression="org.springframework.stereotype.Service" />        
</context:component-scan>

 

以下配置排除包含“DAO”关键字的组件

<context:component-scan base-package="com.lei" >
        <context:exclude-filter type="regex" 
            expression="com.lei.customer.dao.*DAO.*" />        
</context:component-scan>

 

 

 原文:http://www.cnblogs.com/leiOOlei/p/3547589.html

 

分享到:
评论

相关推荐

    springIOC核心组件分析.vsdx

    spring-context-indexer:类管理组件和Classpath扫描 spring-expression:表达式语句 切面编程: spring-aop:面向切面编程,CGLB,JDKProxy spring-aspects:集成AspectJ,Aop应用框架 spring-instrume

    让spring解决控制springboot中bean的加载顺序的问题.docx

    只需要把需要注册进容器的bean声明为@Component即可,spring会自动扫描到这个Bean完成初始化并加载到spring上下文容器。 而当你在项目启动时需要提前做一个业务的初始化工作时,或者你正在开发某个中间件需要完成...

    浅谈Spring装配Bean之组件扫描和自动装配

    本篇文章主要介绍了浅谈Spring装配Bean之组件扫描和自动装配,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

    Spring组件自动扫描详解及实例代码

    Spring组件自动扫描详解及实例代码 问题描述 一个系统往往有成千上万的组件,如果需要手动将所有组件都纳入spring容器中管理,是一个浩大的工程。 解决方案 Spring 提供组件扫描(component scanning)功能。它能...

    Spring in action 实战中文版(第4版)目录修复版

    2.2.2 为组件扫描的bean命名 38 2.2.3 设置组件扫描的基础包 39 2.2.4 通过为bean添加注解实现自动装配 40 2.2.5 验证自动装配 42 2.3 通过Java代码装配 bean 44 2.3.1 创建配置类 44 2.3.2 声明简单的bean ...

    基于框架的Web开发-装配Bean自动装配.doc

    组件扫描(component scanning):Spring会自动发现应用上下文中所创建的bean。 自动装配(autowiring):Spring自动满足bean之间的依赖。 1 使用@Component定义bean 在类声明的前面使用@Component对类进行标注,这...

    华为技术专家整理Spring Boot 注解大全.docx

    @ComponentScan 组件扫描,可自动发现和装配一些 Bean。 @Component 可配合 CommandLineRunner 使用,在程序启动后执行一些基础任务。 @RestController 注解是 @Controller 和 @ResponseBody 的合集, 表示这是个...

    Spring技术内幕:深入解析Spring架构与设计原理(第2部分)

     Spring如何实现各种数据库操作组件的集成?  Spring如何在Web环境中集成IoC容器并为Web应用开发提供利器?  我们耳熟能详的MVC模式在Spring中是如何实现的?  Spring MVC如何灵活地集成各种丰富的视图展现方案...

    Spring 3 Reference中文

    第一部分 Spring framework 概述..5 ... 4.10.4 使用组件定义bean 的元数据.. 99 4.10.5 命名自动检测组件 100 4.10.6 为自动检测组件提供范围. 101 4.10.7 使用注解提供限定符元数据. 102

    Spring核心注解深入解析:提升开发效率

    @Component 和其派生注解(@Repository、@Service、@Controller)标记类为Spring组件,允许Spring通过类路径扫描自动检测和配置这些类。 @Autowired 注解用于自动注入依赖,它可以放置在字段、构造器、setter方法或...

    Spring中文帮助文档

    2.2.5. 在classpath中自动搜索组件 2.3. 面向切面编程(AOP) 2.3.1. 更加简单的AOP XML配置 2.3.2. 对@AspectJ 切面的支持 2.3.3. 对bean命名pointcut( bean name pointcut element)的支持 2.3.4. 对AspectJ装载...

    Spring API

    2.2.5. 在classpath中自动搜索组件 2.3. 面向切面编程(AOP) 2.3.1. 更加简单的AOP XML配置 2.3.2. 对@AspectJ 切面的支持 2.3.3. 对bean命名pointcut( bean name pointcut element)的支持 2.3.4. 对AspectJ装载...

    java-spring-annotations

    XML配置可能很冗长使用注释配置Spring Bean 注释使XML配置最小化扫描组件类Spring将扫描您的Java类以获取特殊注释在Spring容器中自动注册Bean默认Bean ID 您可以显式创建Bean ID 前任。 @Component(“ beanID”) ...

    Spring攻略(第二版 中文高清版).part1

    1.14 从Classpath中扫描组件 50 1.14.1 问题 50 1.14.2 解决方案 51 1.14.3 工作原理 51 1.15 小结 56 第2章 高级Spring IoC容器 57 2.1 调用静态工厂方法创建Bean 57 2.1.1 问题 57 2.1.2 解决...

    ApiBoot为接口服务而生,基于SpringBoot完成扩展、自动化配置,通过封装一系列调用者快速集成组件.zip

    3.自动配置:SpringBoot的自动配置特性利用了Spring对条件化配置的支持,合理地推测应用所需的bean并自动化配置他们。 4.使部署变得简单,SpringBoot内置了三种Servlet容器,Tomcat,Jetty,undertow.我们只需要一个...

    SpringBoot启动过程-mind版.md

    4. **扫描组件:** Spring Boot会扫描项目中的类,查找带有特定注解(如`@Controller`、`@Service`等)的类,并将其注册为Spring的Bean,以便后续的依赖注入和管理。 5. **启动内嵌服务器:** 如果应用是一个Web...

    Spring攻略(第二版 中文高清版).part2

    1.14 从Classpath中扫描组件 50 1.14.1 问题 50 1.14.2 解决方案 51 1.14.3 工作原理 51 1.15 小结 56 第2章 高级Spring IoC容器 57 2.1 调用静态工厂方法创建Bean 57 2.1.1 问题 57 2.1.2 解决...

    Spring Boot 注解

    一 、注解列表 @SpringBootApplication: 包含了@ComponentScan、@Configuration和@EnableAutoConfiguration注解。...@ComponentScan: 组件扫描,可自动发现和配置一些Bean。 @Component: 可配合CommandLineRu

    动力节点老杜最新版Spring6框架教程学习资料分享

    第二点:手写组件扫描 第三点:依赖倒置原则DIP 第四点:CGLIB动态代理代码实现 第五点:代码演示事务传播行为 第六点:代码演示事务隔离级别 第七点:Bean的循环依赖 第八点:Spring的八大设计模式 第九点:17种...

    搭建一个springboot通用框架,集成多个组件.zip

    3.自动配置:SpringBoot的自动配置特性利用了Spring对条件化配置的支持,合理地推测应用所需的bean并自动化配置他们。 4.使部署变得简单,SpringBoot内置了三种Servlet容器,Tomcat,Jetty,undertow.我们只需要一个...

Global site tag (gtag.js) - Google Analytics