`

Spring:@ComponentScan 使用

阅读更多

 

编写不易,转载请注明(http://shihlei.iteye.com/blog/2405675)!

 

一 @ComponentScan 概述

扫描指定表下的Component(@Componment,@Configuration,@Service 等等)

 

存在于:org.springframework.context.annotation 包中

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version${spring.version}</version>
</dependency>

 

二 使用Demo


 

(1)数据准备

package:x.demo.spring.context.scan.pack1

package x.demo.spring.context.scan.pack1;

import org.springframework.stereotype.Component;

@Component
public class Component1 {
    
}

package x.demo.spring.context.scan.pack1;

import org.springframework.stereotype.Component;

@Component
public class Component2 {

}

 

package:x.demo.spring.context.scan.pack3

 

package x.demo.spring.context.scan.pack3;

import org.springframework.stereotype.Component;

@Component
public class Component3 {

}

 

(2)触发Demo

方法1 :代码方式集成:通过AnnotationConfigApplicationContext 触发@ComponentScan使用

 

package x.demo.spring.context.scan;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import x.demo.spring.context.scan.pack1.Component2;
import x.demo.spring.context.scan.pack3.Component3;

@ComponentScan(basePackages = {"x.demo.spring.context.scan.pack1"},
        basePackageClasses = {Component3.class},
        excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = Component2.class))
public class ComponentScanAnnotationDemo {

    //打印相关信息
    private static void show(ApplicationContext context) {
        String[] beans = {"component1", "component2", "component3"};

        for (String b : beans) {
            boolean isContains = context.containsBean(b);
            System.out.println(b + " is exist : " + isContains);
            if (isContains) {
                System.out.println(b + " : " + context.getBean(b));
            }
        }
    }

    /**
     * 通过AnnotationConfigApplicationContext 触发@ComponentScan使用
     */
    public static void triggerViaAnnotationConfigApplicationContext() {
        //加载@ComponentScan 的包扫描
        try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();) {
            context.register(ComponentScanAnnotationDemo.class);
            context.refresh();

            show(context);
        }
    }

    public static void main(String[] args) {
        ComponentScanAnnotationDemo.triggerViaAnnotationConfigApplicationContext();
    }
}

 

方法2:xml 方式触发@ComponentScan使用

(a)xml路径:classpath:x.demo.spring.context.scan/spring-scan.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       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.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
    <context:annotation-config/>
    <bean class="x.demo.spring.context.scan.ComponentScanAnnotationDemo"/>
</beans>

 (b)程序:

 

package x.demo.spring.context.scan;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import x.demo.spring.context.scan.pack1.Component2;
import x.demo.spring.context.scan.pack3.Component3;

@ComponentScan(basePackages = {"x.demo.spring.context.scan.pack1"},
        basePackageClasses = {Component3.class},
        excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = Component2.class))
public class ComponentScanAnnotationDemo {

    //打印相关信息
    private static void show(ApplicationContext context) {
        String[] beans = {"component1", "component2", "component3"};

        for (String b : beans) {
            boolean isContains = context.containsBean(b);
            System.out.println(b + " is exist : " + isContains);
            if (isContains) {
                System.out.println(b + " : " + context.getBean(b));
            }
        }
    }

    /**
     * xml 方式触发@ComponentScan使用
     */
    public static void triggerViaXml() {

        try (ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext
                ("classpath:x.demo.spring.context.scan/spring-scan.xml");) {
            show(context);
        }
    }

    public static void main(String[] args) {
        ComponentScanAnnotationDemo.triggerViaXml();
    }
}

 

(3)结果

component1 is exist : true
component1 : x.demo.spring.context.scan.pack1.Component1@17baae6e
component2 is exist : false
component3 is exist : true
component3 : x.demo.spring.context.scan.pack3.Component3@69379752

 

三 常用注解属性设置

     (1)basePackages:指定扫描的包,basePackageClasses:指定扫描的类

 

     (2)useDefaultFilters:取消默认filter设置

      默认Filter自动扫描包下的Component,取消相当于禁用某个扫描

 

     (3)@ComponentScan.Filter:

      指定Filter 规则,可用于excludeFilters 排除Filters ,includeFilters 包含Filters(包含的Filters 在禁用默认Filter使用,否则没有意义) 

 

  • 大小: 177 KB
分享到:
评论

相关推荐

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

    其中 @ComponentScan 让 spring Boot 扫描到 Configuration 类并把它加入到程序上下文。 @Configuration U等同于 spring 的 XML 配置文件;使用 Java 代码可以检查类型安全。 @EnableAutoConfiguration 自动配置。...

    Spring注解 - 52注解 - 原稿笔记

    注解包含: 拦截器 , 过滤器 , 序列化 , @After , @AfterReturning , @AfterThrowing , @annotation , @Around , @Aspect , @Autowired , @Bean , @Before , @Component , @ComponentScan , @ComponentScans , @...

    Spring Boot 注解

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

    使用Spring的注解方式实现AOP实例

    本篇文章主要介绍了使用Spring的注解方式实现AOP实例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

    spring-hotconf:一个很酷的 Spring 库,用于管理内部 Web 应用程序配置

    spring-hotconf 该项目的目标是为 Spring 提供一个库,允许通过 SSH 连接更改内部 Web 应用程序配置。 设置 Maven配置 ... &lt;artifactId&gt;spring-hotconf &lt;version&gt;1.0.0 ... 在您的@Configuration...@ComponentScan(ba

    spring:spring源码阅读-spring源码阅读

    Spring Framework源码阅读 一,环境建设与代码编译 1.在github上克隆代码。 2.打开import-into-idea.md按照该文件中步骤操作。 1.新建一个模块命名spring-src-read 2.在其中测试spring环境是否建成完毕 注意在...

    Spring中 Configuration的使用.docx

    注: (1)、@Bean注解在返回实例的方法上,...(3)、既然@Bean的作用是注册bean对象,那么完全可以使用@Component、@Controller、@Service、@Ripository等注解注册bean,当然需要配置@ComponentScan注解进行自动扫描。

    springExperiments

    Spring注解 @SpringBootApplication : ... @ComponentScan :告诉Spring在此程序包中搜索其他带注释的类,例如控制器或更多配置。 建筑 ./mvnw spring-boot:run &lt;-运行应用程序 ./mvnw clean package

    java-practice:Java初学者练习

    @ComponentScan(basePackageClasses = ..):放在带有@Configuration批注的类中-Spring扫描的软件包-与@Configuration批注一起使用以知道软件包被批注为@Component -参数basePackageClasses = ..或basePackage = ....

    dependency-injection-spring:Spring依赖注入的最简单示例

    没有XML的Spring Dependency Injection示例 最简单的示例Spring Dependency示例如何工作。 对于所有配置,都使用没有任何XML文件的注释。 描述 所有配置都在pooky.projects.AppConfig中 此类需要使用@Configuration...

    spring-session-data-gemfire:Spring会议的 Gemfire 支持

    @ComponentScan @EnableAutoConfiguration @EnableGemfireHttpSession public class Application { public static void main ( String [] args ) { SpringApplication . run( Application . class,args); } ...

    sonar-JAVA检查规则指南.docx

    SonarQube分析Java项目,遵循的基本内置规则;规则为常用激活规则,含bug、漏洞、坏味道三方面不同程度(严重、阻断、主要、次要、提示等级别)。

    springDemo.zip

    @configuration和@bean@componentScan注解,包含了这些注解,详情可以参考博客的解释。

    spring启动componentscan类扫描加载过程

    spring启动componentscan类扫描加载过程—源码分析Java开发Java经验技巧共16页.pdf.zip

    SpringBoot(powernode)(教学视频+源代码)

    4.2.6 @ComponentScan("com.bjpowernode")配置扫描 五、Spring Boot热部署 5.1 什么是热部署 5.2 添加依赖 5.3 配置idea的启动面板 六、Spring Boot的配置文件语法 6.1 首先引入依赖 6.2 创建Weapon类 6.3 pro

    01-StudentApp:学生详细信息使用Spring引导来演示@ComponetScan @Component @Bean注释

    学生详细信息使用Spring Boot演示@ComponetScan @Component @Bean注释与使用低优先级并执行的@Bean注释相比,通过Spring IOC容器分析@component在使spring Bean对象成为对象时具有更高的优先级,并且在@component...

    springboot用法和与各种框架、组件等结合使用,包括springboot的注解分析、路径分析、取得内置对象、项目打包、配置

    Spring Boot 用法及其与各种框架、组件的结合使用 Spring Boot 是一个用于简化 Spring 应用开发的框架,提供了自动配置、独立运行、嵌入式服务器和生产级别的准备特性,使开发和部署变得更加简单和高效。以下是 ...

    总结Spring注解第一篇

    @ComponentScan @Configuration @Conditional @Retention @Documented @Target @Inherited @Bean...默认@ComponentScan会扫描标注这四个注解,将标注这四个注解类的实例对象注入到spring ioc容器中。使用useDefaultFilt

    java面试题--大厂

    @ComponentScan这个注解在Spring中很重要,它对应XML配置中的元素,@ComponentScan的功能 其实就是自动扫描并加载符合条件的组件(比如@Component和@Repository等)或者bean定义,最 终将这些bean定义加载到IoC容器...

    手写spring ioc 终版

    笔者大概花了10天写了这套...支持@Configuration @Component @ComponentScan @Import ImportBeanDefinitionRegistry FactoryBean @Bean @Lazy @Scope @Autowired @Value @Role autowiredMode 循环依赖 循环import, ...

Global site tag (gtag.js) - Google Analytics