基于@ComponentScan注解的使用详解( 二 )


二、使用
1.环境准备创建Maven项目,添加依赖:
<dependencies><!-- https://mvnrepository.com/artifact/org.springframework/spring-context --><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>4.3.26.RELEASE</version></dependency><!-- https://mvnrepository.com/artifact/junit/junit --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency></dependencies>
创建bean,controller,dao,service层,并在类上加上对应的注解,项目结构如下:

基于@ComponentScan注解的使用详解

文章插图
基于@ComponentScan注解的使用详解

文章插图
基于@ComponentScan注解的使用详解

文章插图
基于@ComponentScan注解的使用详解

文章插图

关于@ComponentScan注解的一些细节@ComponentScan注解可以扫描 任意 类 或者 注解 中内部类bean;
要想被扫描的前提是内部类标注了@Component及其相关衍生注解、内部类必须是static修饰,否则扫描不到;如果是注解的内部类则只能是public static修饰
//@Configurationpublic class ProfileConfig {@Component("class1")private static class Class1 {@Beanpublic Class3 class3() {return new Class3();}}@Component("class2")static class Class2 {}//@Component("class3")protected static class Class3 {}//@Component("class4") //出错//protected class Class4 {////}}--------------------------------------------------------@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)//@Beanpublic @interface MyBean {public static final int age1=3; //常量可以int age=2;public abstract String value() default "qwer"; //属性可以//内部类可以@Component@DependsOn("myBean.EventZ") //依赖事件bean的创建,保证该bean在事件bean之后创建//细节:因为是内部类,所以默认bean的id是类名首字母小写,不是eventZ而是myBean.EventZclass EventSource {public EventSource(){System.out.println("事件源创建了...");}}@Component//("eventZ")public static class EventZ {public EventZ(){System.out.println("事件创建了...");}}}
【基于@ComponentScan注解的使用详解】以上为个人经验,希望能给大家一个参考,也希望大家多多支持趣讯吧 。