如何在实际的代码中使Spring组件的特性?

首先,我们将探讨一些 spring 框架中 ioc(inversion of control)的高级特性,特别是组件扫描的相关知识。组件扫描是 spring 框架中一个重要的特性,它可以自动检测并实例化带有特定注解(如 @component, @service, @controller等)的类,并将它们注册为 spring 上下文中的 bean。这里,我们会通过一些详细的例子来阐明这些概念,并且展示如何在实际的代码中使用这些特性。
1. 组件扫描路径
@componentscan 注解是用于指定 spring 在启动时需要扫描的包路径,从而自动发现并注册组件。 我们设置组件扫描路径包括两种方式:
直接指定包名:如 @componentscan(com.example.demo),等同于 @componentscan(basepackages = {com.example.demo}),spring 会扫描指定包下的所有类,并查找其中带有 @component、@service、@repository 等注解的组件,然后将这些组件注册为 spring 容器的 bean。
指定包含特定类的包:如 @componentscan(basepackageclasses = {exampleservice.class}),spring 会扫描 exampleservice 类所在的包以及其所有子包。
接下来,给出了一个完整的例子,说明如何使用第二种方式来设置组件扫描路径。这可以通过设置 @componentscan的basepackageclasses 属性来实现。例如:
@configuration@componentscan(basepackageclasses = {exampleservice.class})public class basepackageclassconfiguration {}以上代码表示,spring 会扫描 exampleservice 类所在的包以及其所有子包。 全部代码如下: 首先,我们创建一个名为 exampleservice 的服务类package com.example.demo.service;import org.springframework.stereotype.service;@servicepublic class exampleservice {}接着在 bean 目录下创建 demodaopackage com.example.demo.bean;import org.springframework.stereotype.component;@componentpublic class demodao {}然后在配置类中设置组件扫描路径package com.example.demo.configuration;import com.example.demo.service.exampleservice;import org.springframework.context.annotation.componentscan;import org.springframework.context.annotation.configuration;@configuration@componentscan(basepackageclasses = exampleservice.class)public class basepackageclassconfiguration {}我们还会创建一个名为 demoapplication 的类,这个类的作用是启动 spring 上下文并打印所有注册的 bean 的名称。package com.example.demo;import com.example.demo.configuration.basepackageclassconfiguration;import org.springframework.context.annotation.annotationconfigapplicationcontext;import java.util.arrays;public class demoapplication { public static void main(string[] args) { annotationconfigapplicationcontext ctx = new annotationconfigapplicationcontext(basepackageclassconfiguration.class); string[] beandefinitionnames = ctx.getbeandefinitionnames(); arrays.stream(beandefinitionnames).foreach(system.out::println); }}运行上述 demoapplication 类的 main 方法,就会在控制台上看到所有注册的 bean 的名称,包括我们刚刚创建的 exampleservice。
现在,如果我们在 exampleservice 类所在的包或者其任意子包下创建一个新的类(例如 testservice),那么这个组件类也会被自动注册为一个 bean。这就是 basepackageclasses 属性的作用:它告诉 spring 要扫描哪些包以及其子包。package com.example.demo.service;import org.springframework.stereotype.service;@servicepublic class testservice {}如果再次运行 demoapplication 类的 main 方法,就会看到 testservice 也被打印出来,说明它也被成功注册为了一个 bean。
我们可以看到这个 demodao 始终没有被扫描到,我们看一下 @componentscan 注解的源码
可以看到 basepackageclasses 属性这是一个数组类型的,有人会疑问了,刚刚我们写的 @componentscan(basepackageclasses = exampleservice.class),这没有用到数组啊,为什么这里还能正常运行呢? 如果数组只包含一个元素,可以在赋值时省略数组的大括号 {},这是 java 的一种语法糖。在这种情况下,编译器会自动把该元素包装成一个数组。 例如,以下两种写法是等价的:@componentscan(basepackageclasses = {exampleservice.class})  

@componentscan(basepackageclasses = exampleservice.class)在上面两种情况下,exampleservice.class 都会被包装成一个只包含一个元素的数组。这是 java 语法的一个便利特性,使得代码在只有一个元素的情况下看起来更加简洁。 那么为了 demodao 组件被扫描到,我们可以在 basepackageclasses 属性加上 demodao 类,这样就可以扫描 demodao 组件所在的包以及它的子包。package com.example.demo.configuration;import com.example.demo.bean.demodao;import com.example.demo.service.exampleservice;import org.springframework.context.annotation.componentscan;import org.springframework.context.annotation.configuration;@configuration@componentscan(basepackageclasses = {exampleservice.class, demodao.class})public class basepackageclassconfiguration {}运行结果
@componentscan 注解的源码还有不少,后面我们用到再说  
2. 按注解过滤组件(包含)
除了基本的包路径扫描,spring 还提供了过滤功能,允许我们通过设定过滤规则,只包含或排除带有特定注解的类。
这个过滤功能对于大型项目中的模块划分非常有用,可以精细控制 spring 的组件扫描范围,优化项目启动速度。 在 spring 中可以通过 @componentscan 的 includefilters 属性来实现注解包含过滤,只包含带有特定注解的类。
在下面这个例子中,我们将创建一些带有特定注解的组件,并设置一个配置类来扫描它们。 全部代码如下: 创建一个新的注解 species:
package com.example.demo.annotation;import java.lang.annotation.elementtype;import java.lang.annotation.retention;import java.lang.annotation.retentionpolicy;import java.lang.annotation.target;@retention(retentionpolicy.runtime)@target(elementtype.type)public @interface species {}接下来,我们将创建三个不同的组件,其中两个包含 species 注解:package com.example.demo.bean;import com.example.demo.annotation.species;import org.springframework.stereotype.component;@speciespublic class elephant {}elephant 类被 @species 修饰,没有 @component 修饰。package com.example.demo.bean;import org.springframework.stereotype.component;@componentpublic class monkey {}monkey 只被 @component 修饰package com.example.demo.bean;import com.example.demo.annotation.species;import org.springframework.stereotype.component;@component@speciespublic class tiger {}如上所示,tiger 有 @component 和 @species 修饰。 接着,我们需要创建一个配置类,用于扫描和包含有 species 注解的组件:package com.example.demo.configuration;import com.example.demo.annotation.species;import org.springframework.context.annotation.componentscan;import org.springframework.context.annotation.componentscan.filter;import org.springframework.context.annotation.configuration;import org.springframework.context.annotation.filtertype;@configuration@componentscan(basepackages = com.example.demo, includefilters = @filter(type = filtertype.annotation, classes = species.class), usedefaultfilters = false)public class filterconfiguration {}在这个配置类中,我们设置了 @componentscan 注解的 includefilters 属性,filtertype.annotation 代表按注解过滤,这里用于扫描包含所有带有 species 注解的组件。注意,usedefaultfilters = false 表示禁用了默认的过滤规则,只会包含标记为 species 的组件。
有人可能会疑问了,usedefaultfilters = false 表示禁用了默认的过滤规则,什么是默认的过滤规则? 在 spring 中,当使用 @componentscan 注解进行组件扫描时,spring 提供了默认的过滤规则。这些默认规则包括以下几种类型的注解:  
@component
@repository
@service
@controller
@restcontroller
@configuration
默认不写 usedefaultfilters 属性的情况下,usedefaultfilters 属性的值为 true,spring 在进行组件扫描时会默认包含以上注解标记的组件,如果将 usedefaultfilters 设置为 false,spring 就只会扫描明确指定过滤规则的组件,不再包括以上默认规则的组件。
所以,usedefaultfilters = false 是在告诉 spring 我们只想要自定义组件扫描规则。 最后,我们创建一个主程序,来实例化应用上下文并列出所有的 bean 名称:
package com.example.demo;import com.example.demo.configuration.filterconfiguration;import org.springframework.context.applicationcontext;import org.springframework.context.annotation.annotationconfigapplicationcontext;public class demoapplication { public static void main(string[] args) { applicationcontext ctx = new annotationconfigapplicationcontext(filterconfiguration.class); string[] beannames = ctx.getbeandefinitionnames(); for (string beanname : beannames) { system.out.println(beanname); } }}当我们运行这个程序时,会看到输出的 bean 名字只包括被 species 注解标记的类。在这个例子中会看到 tiger 和 elephant,但不会看到 monkey,因为我们的配置只包含了被 species 注解的类。 运行结果:
如果 usedefaultfilters 属性设置为 true,那么运行程序时输出的 bean 名字将会包括 monkey。 总结:上面介绍了如何使用 spring 的 @componentscan 注解中的 includefilters 属性和 usedefaultfilters 属性来过滤并扫描带有特定注解的类。
通过自定义注解和在配置类中设置相关属性,可以精确地控制哪些类被 spring 容器扫描和管理。如果设置 usedefaultfilters 为 false,则 spring 只扫描被明确指定过滤规则的组件,不再包含默认规则(如 @component、@service 等)的组件。  
3. 按注解过滤组件(排除)
在 spring 框架中,我们不仅可以通过 @componentscan 注解的 includefilters 属性设置包含特定注解的类,还可以通过 excludefilters 属性来排除带有特定注解的类。这个功能对于我们自定义模块的加载非常有用,我们可以通过这种方式,精确控制哪些组件被加载到 spring 的 ioc 容器中。
下面我们将通过一个具体的示例来说明如何使用 @componentscan 的 excludefilters 属性来排除带有特定注解的类。 全部代码如下: 首先,创建一个注解 exclude:
package com.example.demo.annotation;import java.lang.annotation.elementtype;import java.lang.annotation.retention;import java.lang.annotation.retentionpolicy;import java.lang.annotation.target;@target({elementtype.type})@retention(retentionpolicy.runtime)public @interface exclude {}定义三个类 elephant、monkey 、tigerpackage com.example.demo.bean;import com.example.demo.annotation.exclude;import org.springframework.stereotype.component;@component@excludepublic class elephant {}package com.example.demo.bean;import org.springframework.stereotype.component;@componentpublic class monkey {}package com.example.demo.bean;import org.springframework.stereotype.component;@componentpublic class tiger {}注意,这几个类都标记为 @component,elephant 类上有 @exclude 注解。 接下来,我们创建配置类 filterconfiguration,在其中使用 @componentscan 注解,并通过 excludefilters 属性排除所有标记为 @exclude 的类:package com.example.demo.configuration;import com.example.demo.annotation.exclude;import org.springframework.context.annotation.componentscan;import org.springframework.context.annotation.configuration;import org.springframework.context.annotation.filtertype;@configuration@componentscan(basepackages = com.example.demo, excludefilters = @componentscan.filter(type = filtertype.annotation, classes = exclude.class))public class filterconfiguration {}这样,在 spring ioc 容器中,只有 tiger 和 monkey 类会被扫描并实例化,因为 elephant 类被 @exclude 注解标记,而我们在 filterconfiguration 类中排除了所有被 @exclude 注解标记的类。 主程序为:package com.example.demo;import com.example.demo.configuration.filterconfiguration;import org.springframework.context.applicationcontext;import org.springframework.context.annotation.annotationconfigapplicationcontext;public class demoapplication { public static void main(string[] args) { applicationcontext ctx = new annotationconfigapplicationcontext(filterconfiguration.class); string[] beannames = ctx.getbeandefinitionnames(); for (string beanname : beannames) { system.out.println(beanname); } }}运行结果:
总结:这小节主要讲解了如何在 spring 框架中通过 @componentscan 注解的 excludefilters 属性进行注解过滤,以精确控制加载到 spring ioc 容器中的组件。在本小节的示例中,我们首先创建了一个名为 exclude 的注解,然后定义了三个类 elephant、monkey、和 tiger,它们都被标记为 @component,其中 elephant 类上还有一个 @exclude 注解。
接下来,我们创建了一个配置类 filterconfiguration,其中使用了 @componentscan 注解,并通过 excludefilters 属性排除了所有标记为 @exclude 的类。因此,当程序运行时,spring ioc 容器中只有 tiger 和 monkey 类会被扫描并实例化,因为 elephant 类被 @exclude 注解标记,所以被排除了。  
4. 通过正则表达式过滤组件
在 spring 框架中,除了可以通过指定注解来进行包含和排除类的加载,我们还可以利用正则表达式来对组件进行过滤。这种方式提供了一种更灵活的方式来选择需要被 spring ioc 容器管理的类。具体来说,可以利用正则表达式来包含或者排除名称符合某个特定模式的类。
下面,我们将通过一个具体的例子来展示如何使用正则表达式过滤来只包含类名以特定字符串结尾的类。 下面的例子将演示如何只包含类名以 tiger 结尾的类。 全部代码如下: 定义三个类 tiger 、elephant 、monkey
package com.example.demo.bean;import org.springframework.stereotype.component;@componentpublic class elephant {}package com.example.demo.bean;import org.springframework.stereotype.component;@componentpublic class monkey {}package com.example.demo.bean;import org.springframework.stereotype.component;@componentpublic class tiger {}接着我们创建配置类 filterconfiguration,使用 @componentscan 注解,并通过 includefilters 属性来包含类名以 tiger 结尾的类:package com.example.demo.configuration;import org.springframework.context.annotation.componentscan;import org.springframework.context.annotation.configuration;import org.springframework.context.annotation.filtertype;@configuration@componentscan(basepackages = com.example.demo, usedefaultfilters = false, includefilters = @componentscan.filter(type = filtertype.regex, pattern = .*tiger))public class filterconfiguration {}在上述示例中,我们使用 filtertype.regex 过滤类型,并指定要包含的正则表达式模式 .*tiger。结果只会有 tiger 类会被 spring的ioc 容器扫描并实例化,因为只有 tiger 类的类名满足正则表达式 .*tiger。这里. 代表任意单个字符 (除了换行符),* 代表前一个字符重复任意次,.* 组合起来表示匹配任意个任意字符。 主程序:package com.example.demo;import com.example.demo.configuration.filterconfiguration;import org.springframework.context.applicationcontext;import org.springframework.context.annotation.annotationconfigapplicationcontext;public class demoapplication { public static void main(string[] args) { applicationcontext ctx = new annotationconfigapplicationcontext(filterconfiguration.class); string[] beannames = ctx.getbeandefinitionnames(); for (string beanname : beannames) { system.out.println(beanname); } }}运行结果
总结:本小节介绍了如何在 spring 框架中使用正则表达式对组件进行过滤,以选择哪些类应被 spring ioc 容器管理。在所给示例中,首先定义了三个类 elephant、monkey 和 tiger。然后创建了一个配置类 filterconfiguration,使用了 @componentscan 注解,并通过 includefilters 属性设置了一个正则表达式  .*tiger,用于选择类名以 tiger 结尾的类。所以在运行主程序时,spring 的 ioc 容器只会扫描并实例化 tiger 类,因为只有 tiger 类的类名满足正则表达式  .*tiger。  
5. assignable 类型过滤组件
assignable 类型过滤 是 spring 框架在进行组件扫描时的一种过滤策略,该策略允许我们指定一个或多个类或接口,然后 spring 会包含或排除所有可以赋值给这些类或接口的类。如果我们指定了一个特定的接口,那么所有实现了这个接口的类都会被包含(或者排除)。同样,如果指定了一个具体的类,那么所有继承自这个类的类也会被包含(或者排除)。 在下面的例子中,我们将使用 “assignable 类型过滤” 来包含所有实现了 animal 接口的类。 全部代码如下: 首先,我们定义一个 animal 接口
package com.example.demo.bean;public interface animal {}接着定义三个类:elephant 、 monkey 和 tiger,其中 tiger 没有实现 animal 接口package com.example.demo.bean;import org.springframework.stereotype.component;@componentpublic class elephant implements animal {}package com.example.demo.bean;import org.springframework.stereotype.component;@componentpublic class monkey implements animal {}package com.example.demo.beanimport org.springframework.stereotype.component;@componentpublic class tiger {}然后,我们创建一个 filterconfiguration 类并使用 @componentscan 来扫描所有实现了 animal 接口的类。package com.example.demo.configuration;import com.example.demo.bean.animal;import org.springframework.context.annotation.componentscan;import org.springframework.context.annotation.configuration;import org.springframework.context.annotation.filtertype;@configuration@componentscan(basepackages = com.example.demo, usedefaultfilters = false, includefilters = @componentscan.filter(type = filtertype.assignable_type, classes = animal.class))public class filterconfiguration {}这种过滤方式在 @componentscan 注解中通过 filtertype.assignable_type 来使用,这里 spring 将只扫描并管理所有实现了 animal 接口的类。 最后,我们创建一个主程序来测试:package com.example.demo;import com.example.demo.configuration.filterconfiguration;import org.springframework.context.applicationcontext;import org.springframework.context.annotation.annotationconfigapplicationcontext;public class demoapplication { public static void main(string[] args) { applicationcontext ctx = new annotationconfigapplicationcontext(filterconfiguration.class); string[] beannames = ctx.getbeandefinitionnames(); for (string beanname : beannames) { system.out.println(beanname); } }}运行结果:
这里也可以看到,只有实现了 animal 接口的类才会被 spring 的 ioc 容器扫描并实例化,其他的 @component 类没有实现 animal 接口的 bean 将不会被扫描和实例化。 总结:本小节介绍了 spring 框架中的 assignable 类型过滤 ,这是一种可以指定一个或多个类或接口进行组件扫描的过滤策略。
spring 会包含或排除所有可以赋值给这些类或接口的类。在本小节的例子中,首先定义了一个 animal 接口,然后定义了三个类 elephant、monkey 和 tiger,其中 elephant 和 monkey 实现了 animal 接口,而 tiger 没有。然后创建了一个 filterconfiguration 类,使用了 @componentscan 注解,并通过 includefilters 属性和 filtertype.assignable_type 类型来指定扫描所有实现了 animal 接口的类。
因此,当运行主程序时,spring 的 ioc 容器只会扫描并实例化实现了 animal 接口的 elephant 和 monkey 类,未实现 animal 接口的 tiger 类不会被扫描和实例化。  
6. 自定义组件过滤器
spring 也允许我们定义自己的过滤器来决定哪些组件将被 spring ioc 容器扫描。为此,我们需要实现 typefilter 接口,并重写 match() 方法。在 match() 方法中,我们可以自定义选择哪些组件需要被包含或者排除。 全部代码如下: 新增一个接口 animal
package com.example.demo.bean;public interface animal { string gettype();}定义几个类,实现 animal 接口package com.example.demo.bean;import org.springframework.stereotype.component;@componentpublic class elephant implements animal { public string gettype() { return this is a elephant.; }}package com.example.demo.bean;import org.springframework.stereotype.component;@componentpublic class monkey implements animal { public string gettype() { return this is an monkey.; }}package com.example.demo.bean;import org.springframework.stereotype.component;@componentpublic class tiger implements animal { public string gettype() { return this is a tiger.; }}package com.example.demo.bean;import org.springframework.stereotype.component;@componentpublic class tiger2 { public string gettype() { return this is a tiger2.; }}tiger2 没实现 animal 接口,后面用来对比。 下面我们先个自定义一个过滤器 customfilter,它实现了 typefilter 接口,这个过滤器会包含所有实现了 animal 接口并且类名以 t 开头的类:package com.example.demo.filter;import com.example.demo.bean.animal;import org.springframework.core.type.classmetadata;import org.springframework.core.type.classreading.metadatareader;import org.springframework.core.type.classreading.metadatareaderfactory;import org.springframework.core.type.filter.typefilter;import java.io.ioexception;import java.util.arrays;public class customfilter implements typefilter { @override public boolean match(metadatareader metadatareader, metadatareaderfactory metadatareaderfactory) throws ioexception { classmetadata classmetadata = metadatareader.getclassmetadata(); // 如果全限定类名以 t 开头并且实现了 animal 接口 return classmetadata.getclassname().startswith(com.example.demo.bean.t) && arrays.aslist(classmetadata.getinterfacenames()).contains(animal.class.getname()); }}如果 match 方法返回 true,那么 spring 将把这个类视为候选组件,还需满足其他条件才能创建 bean,如果这个类没有使用 @component、@service 等注解,那么即使过滤器找到了这个类,spring 也不会将其注册为 bean。因为 spring 依然需要识别类的元数据(如:@component、@service 等注解)来确定如何创建和管理 bean。反之,如果 match 方法返回 false,那么 spring 将忽略这个类。 在 match 方法中  
metadatareader.getclassmetadata() 返回一个 classmetadata 对象,它包含了关于当前类的一些元数据信息,例如类名、是否是一个接口、父类名等。
classmetadata.getclassname() 返回当前类的全限定类名,也就是包括了包名的类名。
在 match 方法中,我们检查了当前类的全限定名是否以 com.example.demo.bean.t 开头,并且当前类是否实现了 animal 接口。如果满足这两个条件,match 方法就返回 true,spring 会将这个类视为候选组件。如果这两个条件有任何一个不满足,match 方法就返回 false,spring 就会忽略这个类,不会将其视为候选组件。 然后,在我们的 filterconfiguration 中,使用 filtertype.custom 类型,并且指定我们刚才创建的 customfilter 类:
package com.example.demo.configuration;import com.example.demo.filter.customfilter;import org.springframework.context.annotation.componentscan;import org.springframework.context.annotation.configuration;import org.springframework.context.annotation.filtertype;@configuration@componentscan(basepackages = com.example.demo, usedefaultfilters = false, includefilters = @componentscan.filter(type = filtertype.custom, classes = customfilter.class))public class filterconfiguration {}这样,当 spring ioc 容器进行扫描的时候,只有类名以 t 开头并且实现了 animal 接口的组件才会被包含。在我们的例子中,只有 tiger 类会被包含,tiger2、elephant 和 monkey 类将被排除。 主程序:package com.example.demo;import com.example.demo.configuration.filterconfiguration;import org.springframework.context.applicationcontext;import org.springframework.context.annotation.annotationconfigapplicationcontext;public class demoapplication { public static void main(string[] args) { applicationcontext ctx = new annotationconfigapplicationcontext(filterconfiguration.class); string[] beannames = ctx.getbeandefinitionnames(); for (string beanname : beannames) { system.out.println(beanname); } }}运行结果:
调试会发现,match 方法在不停的回调。其实 match 方法的调用次数和 spring 应用上下文中的 bean 定义数量是相关的,当我们使用 @componentscan 进行包扫描时,spring 会遍历指定包(及其子包)下的所有类,对每个类进行分析以决定是否需要创建对应的 bean。
当我们使用 @componentscan.filter 定义自定义的过滤器时,spring 会为每个遍历到的类调用过滤器的 match 方法,以决定是否需要忽略这个类。因此,match 方法被调用的次数等于 spring 扫描到的类的数量,不仅包括最终被创建为 bean 的类,也包括被过滤器忽略的类。
这个行为可能受到一些其他配置的影响。例如,如果 spring 配置中使用了懒加载 (@lazy),那么 match 方法的调用可能会被延迟到 bean 首次被请求时。 总结:本小节介绍了如何在 spring 框架中创建和使用自定义过滤器,以决定哪些组件将被 spring ioc 容器视为候选组件。
通过实现 typefilter 接口并重写其 match() 方法,可以根据自定义的条件决定哪些类会被包含在候选组件的列表中。在这个例子中,我们创建了一个自定义过滤器,只有以 t 开头且实现了 animal 接口的类才会被标记为候选组件。当 spring 进行包扫描时,会遍历所有的类,并对每个类调用过滤器的 match() 方法,这个方法的调用次数等于 spring 扫描到的类的数量。
然后,只有那些同时满足过滤器条件并且被 spring 识别为组件的类(例如,使用了 @component 或 @service 等注解),才会被实例化为 bean 并被 spring ioc 容器管理。如果配置了懒加载,那么 bean 的实例化可能会被延迟到 bean 首次被请求时。  
7. 组件扫描的其他特性
spring 的组件扫描机制提供了一些强大的特性,我们来逐一讲解。
7.1 组合使用组件扫描
spring 提供了 @componentscans 注解,让我们能够组合多个 @componentscan 使用,这样可以让我们在一次操作中完成多次包扫描。 @componentscans 的主要使用场景是当需要对 spring 的组件扫描行为进行更精细的控制时,可以在同一个应用程序中扫描两个完全独立的包,也可以在应用多个独立的过滤器来排除或包含特定的组件。
可以看到 @componentscans 注解接收了一个 componentscan 数组,也就是一次性组合了一堆 @componentscan 注解。 让我们通过一个例子来看看如何使用 @componentscans 来组合多个 @componentscan。 全部代码如下: 首先,我们定义两个简单的类,分别在 com.example.demo.bean1 和 com.example.demo.bean2 包中:
package com.example.demo.bean1;import org.springframework.stereotype.component;@componentpublic class beana {}package com.example.demo.bean2;import org.springframework.stereotype.component;@componentpublic class beanb {}然后,我们在配置类中使用 @componentscans 来一次性扫描这两个包:package com.example.demo.configuration;import org.springframework.context.annotation.componentscan;import org.springframework.context.annotation.componentscans;import org.springframework.context.annotation.configuration;@configuration@componentscans({ @componentscan(com.example.demo.bean1), @componentscan(com.example.demo.bean2)})public class appconfig {}  
最后,我们可以测试一下是否成功地扫描到了这两个类:
package com.example.demo;import com.example.demo.bean1.beana;import com.example.demo.bean2.beanb;import com.example.demo.configuration.appconfig;import org.springframework.context.applicationcontext;import org.springframework.context.annotation.annotationconfigapplicationcontext;public class demoapplication { public static void main(string[] args) { applicationcontext ctx = new annotationconfigapplicationcontext(appconfig.class); beana beana = ctx.getbean(beana.class); beanb beanb = ctx.getbean(beanb.class); system.out.println(beana = + beana); system.out.println(beanb = + beanb); }}运行上述 main 方法,beana 和 beanb 就成功地被扫描并注入到了 spring 的 applicationcontext 中。 运行结果:
总结:本小节介绍了 spring 包扫描机制的一个重要特性,即能够使用 @componentscans 注解进行组合包扫描。这个特性允许在一次操作中完成多次包扫描,实现对 spring 组件扫描行为的精细控制。例如,可以同时扫描两个完全独立的包,或者应用多个独立的过滤器来排除或包含特定的组件。在本小节的示例中,使用 @componentscans 一次性扫描了 com.example.demo.bean1 和 com.example.demo.bean2 两个包,成功地将 beana 和 beanb 扫描并注入到 spring 的 applicationcontext 中。  
8. 组件扫描的组件名称生成
当我们在 spring 中使用注解进行 bean 的定义和管理时,通常会用到 @component, @service, @repository, @controller 等注解。在使用这些注解进行 bean 定义的时候,如果我们没有明确指定 bean 的名字,那么 spring 会根据一定的规则为我们的 bean 生成一个默认的名字。 这个默认的名字一般是类名的首字母小写。例如,对于一个类名为 myservice 的类,如果我们像这样使用 @service 注解:
@servicepublic class myservice {}那么 spring 会为我们的 bean 生成一个默认的名字 myservice。我们可以在应用的其他地方通过这个名字来引用这个 bean。例如,我们可以在其他的 bean 中通过 @autowired 注解和这个名字来注入这个 bean:@autowiredprivate myservice myservice;这个默认的名字是通过 beannamegenerator 接口的实现类 annotationbeannamegenerator 来生成的。annotationbeannamegenerator 会检查我们的类是否有明确的指定了 bean 的名字,如果没有,那么它就会按照类名首字母小写的规则来生成一个默认的名字。  
8.1 spring 是如何生成默认 bean 名称的(源码分析)
为了解释这个过程,让我们看一下 annotationbeannamegenerator 类的源码,以下源码对应的 spring 版本是 5.3.7。 先给出源码图片,后面给出源码分析
代码块提出来分析:
public string generatebeanname(beandefinition definition, beandefinitionregistry registry) { if (definition instanceof annotatedbeandefinition) { // 该行检查beandefinition是否为annotatedbeandefinition string beanname = this.determinebeannamefromannotation((annotatedbeandefinition)definition); // 该行调用方法来从注解获取bean名称 if (stringutils.hastext(beanname)) { // 检查是否获取到了有效的bean名称 return beanname; // 如果有,返回这个名称 } } return this.builddefaultbeanname(definition, registry); // 如果没有从注解中获取到有效的名称,调用方法生成默认的bean名称}再看看 determinebeannamefromannotation 方法
这段代码很长,我们直接将代码块提出来分析:
@nullableprotected string determinebeannamefromannotation(annotatedbeandefinition annotateddef) { // 1. 获取bean定义的元数据,包括所有注解信息 annotationmetadata amd = annotateddef.getmetadata(); // 2. 获取所有注解类型 set types = amd.getannotationtypes(); // 3. 初始化bean名称为null string beanname = null; // 4. 遍历所有注解类型 iterator var5 = types.iterator(); while(var5.hasnext()) { // 4.1 获取当前注解类型 string type = (string)var5.next(); // 4.2 获取当前注解的所有属性 annotationattributes attributes = annotationconfigutils.attributesfor(amd, type); // 4.3 只有当前注解的属性不为null时,才会执行以下代码 if (attributes != null) { set metatypes = (set)this.metaannotationtypescache.computeifabsent(type, (key) -> { set result = amd.getmetaannotationtypes(key); return result.isempty() ? collections.emptyset() : result; }); // 4.4 检查当前注解是否为带有名称的元注解 if (this.isstereotypewithnamevalue(type, metatypes, attributes)) { // 4.5 尝试从注解的value属性中获取bean名称 object value = attributes.get(value); if (value instanceof string) { string strval = (string)value; // 4.6 检查获取到的名称是否为有效字符串 if (stringutils.haslength(strval)) { // 4.7 如果已经存在bean名称并且与当前获取到的名称不一致,则抛出异常 if (beanname != null && !strval.equals(beanname)) { throw new illegalstateexception(stereotype annotations suggest inconsistent component names: ' + beanname + ' versus ' + strval + '); } // 4.8 设置bean名称为获取到的名称 beanname = strval; } } } } } // 5. 返回获取到的bean名称,如果没有找到有效名称,则返回null return beanname;}最后看看 builddefaultbeanname 方法,spring 是如何生成 bean 的默认名称的。
拆成代码块分析:protected string builddefaultbeanname(beandefinition definition) { // 1. 从bean定义中获取bean的类名 string beanclassname = definition.getbeanclassname(); // 2. 确保bean类名已设置,否则会抛出异常 assert.state(beanclassname != null, no bean class name set); // 3. 使用spring的classutils获取类的简单名称,即不带包名的类名 string shortclassname = classutils.getshortname(beanclassname); // 4. 使用java内省工具(introspector)将类名首字母转换为小写 // 这就是spring的默认bean命名策略,如果用户没有通过@component等注解显式指定bean名, // 则会使用该类的非限定类名(即不带包名的类名),并将首字母转换为小写作为bean名。 return introspector.decapitalize(shortclassname);}8.2 生成默认 bean 名称的特殊情况 大家肯定知道 userservice 默认 bean 名称为 userservice,但如果类名为 mservice,bean 名称还是 mservice,不会首字母小写。具体原因,我们来分析一下。 我们上面分析 builddefaultbeanname 方法生成默认 bean 名称的时候,发现里面有调用 decapitalize 方法后再返回,我们来看看 decapitalize 方法。
提出代码块分析一下
/** * 将字符串转换为正常的 java 变量名规则的形式。 * 这通常意味着将第一个字符从大写转换为小写, * 但在(不常见的)特殊情况下,当有多个字符并且第一个和第二个字符都是大写时,我们将保持原样。 * 因此,“foobah”变为“foobah”,“x”变为“x”,但“url”保持为“url”。 * 这是 java 内省机制的一部分,因为它涉及 java 对类名和变量名的默认命名规则。 * 根据这个规则,我们可以从类名自动生成默认的变量名。 * * @param name 要小写的字符串。 * @return 小写版本的字符串。 */public static string decapitalize(string name) { if (name == null || name.length() == 0) { return name; } // 如果字符串的前两个字符都是大写,那么保持原样 if (name.length() > 1 && character.isuppercase(name.charat(1)) && character.isuppercase(name.charat(0))) { return name; } char chars[] = name.tochararray(); // 将第一个字符转为小写 chars[0] = character.tolowercase(chars[0]); return new string(chars);}根据 java 的命名规则,类名的首字母应该大写,而变量名的首字母应该小写,它告诉内省机制如何从类名生成默认的变量名(或者说 bean 名)。 这里可以看到, decapitalize 方法接收一个字符串参数,然后将这个字符串的首字母转为小写,除非这个字符串的前两个字符都是大写,这种情况下,字符串保持不变。 所以,在 java 内省机制中,如果类名的前两个字母都是大写,那么在进行首字母小写的转换时,会保持原样不变。也就是说,对于这种情况,bean 的名称和类名是一样的。 这种设计是为了遵守 java 中的命名约定,即当一个词作为类名的开始并且全部大写时(如 url,http),应保持其全部大写的格式。  
9. java 的内省机制在生成默认 bean 名称中的应用
java 内省机制(introspection)是 java 语言对 bean 类的一种自我检查的能力,它属于 java 反射的一个重要补充。它允许 java 程序在运行时获取 bean 类的类型信息以及 bean 的属性和方法的信息。注意:“内省” 发音是 nèi xǐng。 内省机制的目的在于提供一套统一的 api,可以在运行时动态获取类的各种信息,主要涵盖以下几个方面:
获取类的类型信息:可以在运行时获取任意一个 bean 对象所属的类、接口、父类、修饰符等信息。
属性信息:可以获取 bean 类的属性的各种信息,如类型、修饰符等。
获取方法信息:可以获取 bean 类的方法信息,如返回值类型、参数类型、修饰符等。
调用方法:可以在运行时调用任意一个 bean 对象的方法。
修改属性值:可以在运行时修改 bean 的属性值。
通过这些反射 api,我们可以以一种统一的方式来操作任意一个对象,无需对对象的具体类进行硬编码。 在命名规则上,当我们获取一个 bean 的属性名时,如果相应的 getter 或 setter 方法的名称除去 get/set 前缀后,剩余部分的第一个字母是大写的,那么在转换成属性名时,会将这个字母变为小写。如果剩余部分的前两个字母都是大写的,属性名会保持原样不变,不会将它们转换为小写。 这个规则主要是为了处理一些类名或方法名使用大写字母缩写的情况。例如,对于一个名为 geturl“的方法,我们会得到”url“作为属性名,而不是”url。 虽然在日常开发中我们可能不会直接频繁使用到 java 的内省机制,但在一些特定的场景和工具中,内省机制却发挥着重要作用:
ide 和调试工具:这些工具需要利用内省机制来获取类的信息,如类的层次结构、方法和属性信息等,以便提供代码补全、代码检查等功能。
测试框架:例如 junit 这样的测试框架需要通过内省机制来实例化测试类,获取测试方法等信息以进行测试的运行。
依赖注入框架:比如 spring 等依赖注入框架需要利用内省机制来扫描类,获取类中的依赖关系定义,并自动装配 bean。
序列化 / 反序列化:序列化需要获取对象的类型信息和属性信息来实现对象状态的持久化;反序列化需要利用类型信息来还原对象。
日志框架:很多日志框架可以通过内省机制自动获取日志方法所在类、方法名等上下文信息。
访问权限判断:一些安全相关的框架需要通过内省判断一个成员的访问权限是否合法。
面向接口编程:内省机制使得在面向接口编程的时候可以不需要 hardcode 接口的实现类名,而是在运行时定位。
简言之,内省机制的目的是实现跨类的动态操作和信息访问,提高运行时的灵活性。这也使得框架在不知道具体类的情况下,可以进行一些有用的操作。


光纤成为智慧地产发展重要基石,实现真千兆网络全屋覆盖
天玑1000+发布 联发科旗舰升级显露新动机
江西TFT-LCD面板项目出现变故,韩企、中建齐入坑
“中国版特斯拉”年销10万辆,胜算几何?
我国嫦娥五号“挖土”归来有多艰难?
如何在实际的代码中使Spring组件的特性?
意法半导体推出因数控制器,以模拟技术来满足工业需求
IEK ITIS:09年台湾地区汽车产业总产值达2,490亿
世界末日自救手册,介绍十种应付灾难的新技术
双向晶闸管和普通晶闸管的区别
什么是交流电机控制?
PCB布线设计时如何通过线长匹配来保证系统的时序
ADC/DAC 卡桥接模拟和数字带宽鸿沟
2022年千元内蓝牙耳机哪款好?千元内高质量蓝牙耳机推荐
引光学产业新星,蓄发展强劲动能——昇旸光学落子南浔国际人才产业园
闪电网络是什么?比特币和闪电网络对比
马斯克的特斯拉私有化计划资金是否有保障?
运放是什么?运放怎么选?运放应用有哪些“坑”?
浅谈不同场景下SQPI PSRAM新型存储器如何提升STM32性能
悄然席卷企业级SSD市场的RISC-V主控