(二)活用ComponentScan
项目改造成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 — 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
* — 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的更多相关文章
- BC追踪
项目又要开始改造了,记录一下改造过程中碰到的坑和解决思路,避免以后回头看看自己的笔记都不知道写了什么. (一)敏感信息混淆 (二)活用ComponentScan (三)Swagger配置多项目共用 ( ...
- HTML5 五子棋 - JS/Canvas 游戏
背景介绍 因为之前用c#的winform中的gdi+,java图形包做过五子棋,所以做这个逻辑思路也就驾轻就熟,然而最近想温故html5的canvas绘图功能(公司一般不用这些),所以做了个五子棋,当 ...
- annotation-config, annotation-driven, compont-scan 区别
<annotaion-driven/>标签: 这个标签对应的实现类是org.springframework.web.servlet.config.AnnotationDrivenBeanD ...
- Java编程配置思路详解
Java编程配置思路详解 SpringBoot虽然提供了很多优秀的starter帮助我们快速开发,可实际生产环境的特殊性,我们依然需要对默认整合配置做自定义操作,提高程序的可控性,虽然你配的不一定比官 ...
- Python:游戏:五子棋之人机对战
本文代码基于 python3.6 和 pygame1.9.4. 五子棋比起我之前写的几款游戏来说,难度提高了不少.如果是人与人对战,那么,电脑只需要判断是否赢了就可以.如果是人机对战,那你还得让电脑知 ...
- python五子棋
以后不更新了,把以前的一些东西发出来. 这是一个命令行环境的五子棋程序.使用了minimax算法. 除了百度各个棋型的打分方式,所有代码皆为本人所撸.本程序结构与之前的井字棋.黑白棋一模一样. 有一点 ...
- 【微信小程序项目实践总结】30分钟从陌生到熟悉 web app 、native app、hybrid app比较 30分钟ES6从陌生到熟悉 【原创】浅谈内存泄露 HTML5 五子棋 - JS/Canvas 游戏 meta 详解,html5 meta 标签日常设置 C#中回滚TransactionScope的使用方法和原理
[微信小程序项目实践总结]30分钟从陌生到熟悉 前言 我们之前对小程序做了基本学习: 1. 微信小程序开发07-列表页面怎么做 2. 微信小程序开发06-一个业务页面的完成 3. 微信小程序开发05- ...
- lch 儿童围棋课堂 初级篇2 (李昌镐 著)
第1章 吃子 第2章 死活:实战演练 第3章 劫争 第4章 布局:定式篇 第5章 布局:三线,四线和大场 第6章 布局:布局类型与形势判断 第7章 中盘:分断 第8章 官子:价值的计算 第9章 对杀技 ...
- Spring中通配符问题
一.加载路径中的通配符 (1)?(匹配单个字符) (2)*(匹配除/外任意字符) (3)**/(匹配任意多个目录) 示例: (1)classpath:app-Beans.xml 说明:无通配符,必须完 ...
随机推荐
- Intellij IDEA +genymotion安装配置
Intellij IDEA是一款非常好用的java编辑器,比Eclipse的代码提示要友善的多,优缺点不多讲了. 下面讲如何安装配置. 1)如官网下载最新版本 http://www.jetbrains ...
- java 模拟实现消费者和生产者问题
题目要求 用java代码模拟实现:一个人不断往箱子里放苹果,另一个人不断从箱子里取苹果,箱子只能放5个苹果,苹果数量无限.要求不使用java.util.concurrent包中的类. 思路 这道题主要 ...
- Python函数(1)
一.Python函数介绍 函数时组织好的,可重复的,用来实现单一,或相关联功能的代码段. 函数的使用原则时先定义,后调用:事先准备工具的过程即函数的定义,遇到应用场景拿来当工具用即函数的调用. 函数的 ...
- JSON 与 XML基本了解
简单了解JSON 和 XML ,以及他们的区别: JSON:是一种轻量级的数据交换格式,ECMA(欧洲计算机制造商协会)的一个子集: 优点:轻量级.占用宽带小.易于人的阅读和编写,便于js解析,支 ...
- HTML5 笔记之 HTML5 的常见用法介绍
阅读目录 介绍 网页标题.文章标题.文章段落 介绍 字体大小.字体颜色.字体类型.字体位置.背景颜色 介绍 插入图片 介绍 网页内的超链接.网页间的超链接 介绍 有序列表.无序列表 介绍 表格制作 介 ...
- SQLServer 连接和联合
一.内连接(inner join) 默认省略inner ,内连接是严格过滤,等同where限制,连接两端的表都数据都需要过滤. 二.左外连接(left outer join) 以左表为基准进行数据连接 ...
- 由Asp.Net客户端控件生成的服务器端控件
由Asp.Net客户端控件生成的服务器端控件(也就是给客户端控件添加 runnat="server"),这样的控件既能在js中通过id命.类名获取到,也能在服务器端根据id获取到
- redis笔记(四)
本篇内容主要是简单介绍redis在python中的使用from time import sleep在python代码中使用redis需要导入redis packageimport redis简单的连接 ...
- centos6.5_64bit_tomcat7开机自启
一.创建tomcat脚本 vim /etc/init.d/tomcat 将下面的内容拷到脚本里面 =================================================== ...
- hive自定义UDTF函数叉分函数
hive自定义UDTF函数叉分函数 1.介绍 从聚合体日志中需要拆解出来各子日志数据,然后单独插入到各日志子表中.通过表生成函数完成这一过程. 2.定义ForkLogUDTF 2.1 HiveUtil ...