项目改造成spring cloud项目后,有非常多组件是复用的,比如(一)敏感信息混淆的组件,比如数据库、Redis等配置, 比如常用的api组件Swagger配置。每个微服务组件里都会有若干个组件随机组合拼成,如果我们在每个服务中都对这些可复用的组件复制粘贴也能实现相应功能。但作为一个典型的码农,当然是想write once run anywhere了,有什么办法可以只写一次按需引入呢?为此我们可以活用ComponentScan


先看看ComponentScan的源码介绍:

/**
* Configures component scanning directives for use with @{@link Configuration} classes.
* Provides support parallel with Spring XML's {@code <context:component-scan>} element.
*
* <p>Either {@link #basePackageClasses} or {@link #basePackages} (or its alias
* {@link #value}) may be specified to define specific packages to scan. If specific
* packages are not defined, scanning will occur from the package of the
* class that declares this annotation.
*
* <p>Note that the {@code <context:component-scan>} element has an
* {@code annotation-config} attribute; however, this annotation does not. This is because
* in almost all cases when using {@code @ComponentScan}, default annotation config
* processing (e.g. processing {@code @Autowired} and friends) is assumed. Furthermore,
* when using {@link AnnotationConfigApplicationContext}, annotation config processors are
* always registered, meaning that any attempt to disable them at the
* {@code @ComponentScan} level would be ignored.
*
* <p>See {@link Configuration @Configuration}'s Javadoc for usage examples.
*
* @author Chris Beams
* @author Juergen Hoeller
* @author Sam Brannen
* @since 3.1
* @see Configuration
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Repeatable(ComponentScans.class)
public @interface ComponentScan { /**
* Alias for {@link #basePackages}.
* <p>Allows for more concise annotation declarations if no other attributes
* are needed &mdash; for example, {@code @ComponentScan("org.my.pkg")}
* instead of {@code @ComponentScan(basePackages = "org.my.pkg")}.
*/
@AliasFor("basePackages")
String[] value() default {}; /**
* Base packages to scan for annotated components.
* <p>{@link #value} is an alias for (and mutually exclusive with) this
* attribute.
* <p>Use {@link #basePackageClasses} for a type-safe alternative to
* String-based package names.
*/
@AliasFor("value")
String[] basePackages() default {}; /**
* Type-safe alternative to {@link #basePackages} for specifying the packages
* to scan for annotated components. The package of each class specified will be scanned.
* <p>Consider creating a special no-op marker class or interface in each package
* that serves no purpose other than being referenced by this attribute.
*/
Class<?>[] basePackageClasses() default {}; /**
* The {@link BeanNameGenerator} class to be used for naming detected components
* within the Spring container.
* <p>The default value of the {@link BeanNameGenerator} interface itself indicates
* that the scanner used to process this {@code @ComponentScan} annotation should
* use its inherited bean name generator, e.g. the default
* {@link AnnotationBeanNameGenerator} or any custom instance supplied to the
* application context at bootstrap time.
* @see AnnotationConfigApplicationContext#setBeanNameGenerator(BeanNameGenerator)
*/
Class<? extends BeanNameGenerator> nameGenerator() default BeanNameGenerator.class; /**
* The {@link ScopeMetadataResolver} to be used for resolving the scope of detected components.
*/
Class<? extends ScopeMetadataResolver> scopeResolver() default AnnotationScopeMetadataResolver.class; /**
* Indicates whether proxies should be generated for detected components, which may be
* necessary when using scopes in a proxy-style fashion.
* <p>The default is defer to the default behavior of the component scanner used to
* execute the actual scan.
* <p>Note that setting this attribute overrides any value set for {@link #scopeResolver}.
* @see ClassPathBeanDefinitionScanner#setScopedProxyMode(ScopedProxyMode)
*/
ScopedProxyMode scopedProxy() default ScopedProxyMode.DEFAULT; /**
* Controls the class files eligible for component detection.
* <p>Consider use of {@link #includeFilters} and {@link #excludeFilters}
* for a more flexible approach.
*/
String resourcePattern() default ClassPathScanningCandidateComponentProvider.DEFAULT_RESOURCE_PATTERN; /**
* Indicates whether automatic detection of classes annotated with {@code @Component}
* {@code @Repository}, {@code @Service}, or {@code @Controller} should be enabled.
*/
boolean useDefaultFilters() default true; /**
* Specifies which types are eligible for component scanning.
* <p>Further narrows the set of candidate components from everything in {@link #basePackages}
* to everything in the base packages that matches the given filter or filters.
* <p>Note that these filters will be applied in addition to the default filters, if specified.
* Any type under the specified base packages which matches a given filter will be included,
* even if it does not match the default filters (i.e. is not annotated with {@code @Component}).
* @see #resourcePattern()
* @see #useDefaultFilters()
*/
Filter[] includeFilters() default {}; /**
* Specifies which types are not eligible for component scanning.
* @see #resourcePattern
*/
Filter[] excludeFilters() default {}; /**
* Specify whether scanned beans should be registered for lazy initialization.
* <p>Default is {@code false}; switch this to {@code true} when desired.
* @since 4.1
*/
boolean lazyInit() default false; /**
* Declares the type filter to be used as an {@linkplain ComponentScan#includeFilters
* include filter} or {@linkplain ComponentScan#excludeFilters exclude filter}.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({})
@interface Filter { /**
* The type of filter to use.
* <p>Default is {@link FilterType#ANNOTATION}.
* @see #classes
* @see #pattern
*/
FilterType type() default FilterType.ANNOTATION; /**
* Alias for {@link #classes}.
* @see #classes
*/
@AliasFor("classes")
Class<?>[] value() default {}; /**
* The class or classes to use as the filter.
* <p>The following table explains how the classes will be interpreted
* based on the configured value of the {@link #type} attribute.
* <table border="1">
* <tr><th>{@code FilterType}</th><th>Class Interpreted As</th></tr>
* <tr><td>{@link FilterType#ANNOTATION ANNOTATION}</td>
* <td>the annotation itself</td></tr>
* <tr><td>{@link FilterType#ASSIGNABLE_TYPE ASSIGNABLE_TYPE}</td>
* <td>the type that detected components should be assignable to</td></tr>
* <tr><td>{@link FilterType#CUSTOM CUSTOM}</td>
* <td>an implementation of {@link TypeFilter}</td></tr>
* </table>
* <p>When multiple classes are specified, <em>OR</em> logic is applied
* &mdash; for example, "include types annotated with {@code @Foo} OR {@code @Bar}".
* <p>Custom {@link TypeFilter TypeFilters} may optionally implement any of the
* following {@link org.springframework.beans.factory.Aware Aware} interfaces, and
* their respective methods will be called prior to {@link TypeFilter#match match}:
* <ul>
* <li>{@link org.springframework.context.EnvironmentAware EnvironmentAware}</li>
* <li>{@link org.springframework.beans.factory.BeanFactoryAware BeanFactoryAware}
* <li>{@link org.springframework.beans.factory.BeanClassLoaderAware BeanClassLoaderAware}
* <li>{@link org.springframework.context.ResourceLoaderAware ResourceLoaderAware}
* </ul>
* <p>Specifying zero classes is permitted but will have no effect on component
* scanning.
* @since 4.2
* @see #value
* @see #type
*/
@AliasFor("value")
Class<?>[] classes() default {}; /**
* The pattern (or patterns) to use for the filter, as an alternative
* to specifying a Class {@link #value}.
* <p>If {@link #type} is set to {@link FilterType#ASPECTJ ASPECTJ},
* this is an AspectJ type pattern expression. If {@link #type} is
* set to {@link FilterType#REGEX REGEX}, this is a regex pattern
* for the fully-qualified class names to match.
* @see #type
* @see #classes
*/
String[] pattern() default {}; } }

其中有以下2个方法可以满足我们需求:

/**
* 默认扫描路径,如果没写则默认扫描当前注释类的包下所有配置
*/
@AliasFor("value") String[] basePackages() default {}; /**
* 扫描指定的包下的某些组件
*/
Class<?>[] basePackageClasses() default {};

那么为了实现我们想要write once run anywhere的目的,就可以对代码进行以下改造:

/**
* @author zhangqiuyang
* Created on 2018/4/8.
*/
@SpringBootApplication
@ComponentScan(basePackages = "com.*.qaqc.zh.ncdt",
basePackageClasses = {
SecretStringJsonCombinedSerializer.class, SecretStringTypeHandler.class,
SwaggerConfig.class, NcdtFilter.class, NcdtSecurityConfig.class,
DBLogAspecter.class, RedisConfig.class
})
public class NcdtApplication { public static void main(String[] args) {
SpringApplication.run(NcdtApplication.class, args);
}
}

  

(二)活用ComponentScan的更多相关文章

  1. BC追踪

    项目又要开始改造了,记录一下改造过程中碰到的坑和解决思路,避免以后回头看看自己的笔记都不知道写了什么. (一)敏感信息混淆 (二)活用ComponentScan (三)Swagger配置多项目共用 ( ...

  2. HTML5 五子棋 - JS/Canvas 游戏

    背景介绍 因为之前用c#的winform中的gdi+,java图形包做过五子棋,所以做这个逻辑思路也就驾轻就熟,然而最近想温故html5的canvas绘图功能(公司一般不用这些),所以做了个五子棋,当 ...

  3. annotation-config, annotation-driven, compont-scan 区别

    <annotaion-driven/>标签: 这个标签对应的实现类是org.springframework.web.servlet.config.AnnotationDrivenBeanD ...

  4. Java编程配置思路详解

    Java编程配置思路详解 SpringBoot虽然提供了很多优秀的starter帮助我们快速开发,可实际生产环境的特殊性,我们依然需要对默认整合配置做自定义操作,提高程序的可控性,虽然你配的不一定比官 ...

  5. Python:游戏:五子棋之人机对战

    本文代码基于 python3.6 和 pygame1.9.4. 五子棋比起我之前写的几款游戏来说,难度提高了不少.如果是人与人对战,那么,电脑只需要判断是否赢了就可以.如果是人机对战,那你还得让电脑知 ...

  6. python五子棋

    以后不更新了,把以前的一些东西发出来. 这是一个命令行环境的五子棋程序.使用了minimax算法. 除了百度各个棋型的打分方式,所有代码皆为本人所撸.本程序结构与之前的井字棋.黑白棋一模一样. 有一点 ...

  7. 【微信小程序项目实践总结】30分钟从陌生到熟悉 web app 、native app、hybrid app比较 30分钟ES6从陌生到熟悉 【原创】浅谈内存泄露 HTML5 五子棋 - JS/Canvas 游戏 meta 详解,html5 meta 标签日常设置 C#中回滚TransactionScope的使用方法和原理

    [微信小程序项目实践总结]30分钟从陌生到熟悉 前言 我们之前对小程序做了基本学习: 1. 微信小程序开发07-列表页面怎么做 2. 微信小程序开发06-一个业务页面的完成 3. 微信小程序开发05- ...

  8. lch 儿童围棋课堂 初级篇2 (李昌镐 著)

    第1章 吃子 第2章 死活:实战演练 第3章 劫争 第4章 布局:定式篇 第5章 布局:三线,四线和大场 第6章 布局:布局类型与形势判断 第7章 中盘:分断 第8章 官子:价值的计算 第9章 对杀技 ...

  9. Spring中通配符问题

    一.加载路径中的通配符 (1)?(匹配单个字符) (2)*(匹配除/外任意字符) (3)**/(匹配任意多个目录) 示例: (1)classpath:app-Beans.xml 说明:无通配符,必须完 ...

随机推荐

  1. 为什么document.write()会清空原来的内容

    为什么document.write()会清空原来的内容: 可能很多朋友都遇到过这样的情况,那就是使用document.write()函数向网页中写内容的时候,会把文档中的原来的内容给清空,这一点对于初 ...

  2. 关于hibernate字段映射@colunm出现的问题以及jpa驼峰大写转_小写的问题探究

    关于hibernate字段映射@colunm出现的问题以及jpa驼峰大写转_小写的问题探究2018年04月24日 15:47:26 守望dfdfdf 阅读数:735 标签: @colunmhibern ...

  3. php session 存储到redis

    PHP 的会话默认是以文件的形式存在的,可以配置到 NoSQL 中,即提高了访问速度,又能很好地实现会话共享,,,爽歪歪! 配置方式如下: 方法一:修改 php.ini 的设置 1 2 session ...

  4. 也谈ThreadLocal

    欢迎赐教博客地址(http://www.cnblogs.com/shizhongtao/p/5358411.html) 对于ThreadLocal使用,网上一堆一堆的.什么内存泄露,什么线程不安全.这 ...

  5. jQuery 浮动导航菜单(购物网站商品类型)

    单页面网页内容较多,页面长度较大,需要方便快速的在页面的不同位置进行定位,所以浮动菜单逐渐流行了起来,如下图 男装.女装.美妆等. 这种菜单功能分为两部分: 1.点击菜单项,网页滚动到对应位置,可简单 ...

  6. 当你的域名是数字开头时如何命名java包路径

    例如:域名是1001y.net 理想的包路径是net.1001y,但由于java命名规范的问题,首字母不能为数字,这时我们只有两种选择: 1,net.$1001y 使用$符号作为首字母. 2,net. ...

  7. SPFieldLookupValue

    //得到查阅项的值SPWeb web = site.OpenWeb();SPList list = web.Lists["DemoList"];SPListItem item = ...

  8. win2008 配置TLS1.2

    配置TLS1.2 提供两种方法, 选择其中一种就行了 1.手动设置 找到HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProv ...

  9. hive自定义UDTF函数叉分函数

    hive自定义UDTF函数叉分函数 1.介绍 从聚合体日志中需要拆解出来各子日志数据,然后单独插入到各日志子表中.通过表生成函数完成这一过程. 2.定义ForkLogUDTF 2.1 HiveUtil ...

  10. Angular2、4入门基础知识(小的概念)

    1. 使用引用符来格式化HTML代码. @Component({ selector: 'app-heroes', templateUrl: './heroes.component.html', sty ...