配置类(启动类)常见的注解解析

144 阅读4分钟

一、@ComponentScan

@ComponentScan主要就是定义扫描的路径从中找出标识了需要装配的类自动装配到spring的bean容器中。

  • 自定扫描路径下边带有@Controller,@Service,@Repository,@Component注解加入spring容器
  • 通过includeFilters加入扫描路径下没有以上注解的类加入spring容器(需设置useDefaultFilters=true
  • 通过excludeFilters过滤出不用加入spring容器的类(需设置useDefaultFilters=true
  • 自定义增加了@Component注解的注解方式
@ComponentScan(value="com.zhang",useDefaultFilters=true,
    includeFilters={
        @Filter(type=FilterType.ANNOTATION,classes={Controller.class}),
        @Filter(type=FilterType.CUSTOM,classes={MyTypeFilter.class})
        //或@ComponentScan.@Filter(type=FilterType.CUSTOM,classes={MyTypeFilter.class})
    })
@Configuration
public class MainScanConfig {
}

其中,@Filter中FilterType包含的类型及意义有:

ANNOTATION:注解类型
ASSIGNABLE_TYPE:ANNOTATION:指定的类型
ASPECTJ:按照Aspectj的表达式,基本上不会用到
REGEX:按照正则表达式
CUSTOM:自定义规则

二、@EnableAutoConfiguration

@EnableAutoConfiguration 注解表示开启自动配置功能,该注解是 Spring Boot 框架@SpringBootApplication注解中包含的三个之一(@Configuration、@EnableAutoConfiguration、

@ComponentScan),也是实现自动化配置的注解。Spring 框架将试图猜测和配置您可能需要的 bean,通常根据您的类路径和定义的 bean 来应用自动配置类。

@EnableAutoConfiguration(exclude = {AdminServerNotifierAutoConfiguration.class, SinoGearCacheAutoConfiguration.class})

拓展:@Configuration该注解表示一个类声明了一个或多个拥有 @Bean注解的方法,并且这些拥有 @Bean的方法的返回对象将被 Spring 容器管理,在其他类中就可以使用 @Autowired注解注入这些 Bean。

@Configuration
public class AppConfig {
    @Bean
    public MyBean myBean() {
        // instantiate, configure and return bean ...
    }
}

三、@EnableConfigurationProperties

@EnableConfigurationProperties注解的作用是:使使用 @ConfigurationProperties 注解的类生效。如果一个配置类只配置@ConfigurationProperties注解,而没有使用@Component,那么在IOC容器中是获取不到properties 配置文件转化的bean。说白了 @EnableConfigurationProperties 相当于把使用 @ConfigurationProperties 的类进行了一次注入,相当于@Component的作用。

@Configuration
@EnableConfigurationProperties(HelloServiceProperties.class)
@ConditionalOnClass(HelloService.class)
@ConditionalOnProperty(prefix = "hello", value = "enable", matchIfMissing = true)
public class HelloServiceAutoConfiguration {
    //配置类
}

@ConfigurationProperties(prefix = "service.properties")
public class HelloServiceProperties {
    //被注入的类
}





@ConfigurationProperties(prefix = "service.properties")
@Component
public class HelloServiceProperties {
    //被注入的类(直接注入)
}

四、@EnableJpaAuditing

在 Spring JPA 中,支持在字段或者方法上进行注解 @CreateDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy

  • @CreateDate:表示该字段为创建时间时间字段,在这个实体被 insert 的时候,会设置默认值
  • @CreatedBy表示该字段为创建人,在这个实体被insert的时候,会设置值。
  • @LastModifiedDate、@LastModifiedBy同理。

使用细节:

  • 实体类上添加 @EntityListeners(AuditingEntityListener.class)
  • 在需要的字段上加上 @CreatedDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy 等注解。
  • 在Xxx Application 启动类上添加 @EnableJpaAuditing
  • 实现 AuditorAware 接口来返回你需要插入的值。重点

五、@EnableSwagger2Doc

引入Swagger2的步骤之一:

  • 在pom.xml中引入依赖
  • 在应用主类中增加@EnableSwagger2Doc注解

六、@EntityScan

@EntityScan 用来扫描和发现指定包及其子包中的Entity定义。其用法如下:

@EntityScan(basePackages = {"com.department.entities","come.employee.entities"})

如果多处使用@EntityScan,它们的basePackages 集合能覆盖所有被Repository使用的Entity即可,集合有交集也没有关系。但是如果不能覆盖被Repository使用的Entity,应用程序启动是会出错,比如:

Not a managed type: com.customer.entities.Customer


七、@EnableJpaRepositories

@EnableJpaRepositories 用来扫描和发现指定包及其子包中的 Repository 定义。其用法如下:

@EnableJpaRepositories(basePackages = {"com.department.repositories","come.employee.repositories"})

如果多处使用@EnableJpaRepositories,它们的basePackages集合不能有交集,并且要能覆盖所有需要的Repository定义。

如果有交集,相应的Repository会被尝试反复注册,从而遇到如下错误:

The bean ‘OrderRepository’, defined in xxx, could not be registered. A bean with that name has already been defined in xxx and overriding is disabled.

如果不能覆盖所有需要的Repository定义,会遇到启动错误:

Parameter 0 of method setCustomerRepository in com.service.CustomerService required a bean of type ‘come.repo.OrderRepository’ that could not be found.


八、@EnableScheduling

与@Scheduled搭配使用:

@EnableScheduling 在类上使用,声明该类下有任务计划
@Scheduled(参数) 在方法上使用,声明该方法属于任务方法

//计划任务执行类
@Service
public class ScheduledTaskService {
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
 
    @Scheduled(fixedRate = 5000) //通过@Scheduled声明该方法是计划任务,使用fixedRate属性每隔固定时间执行
    public void reportCurrentTime(){
        System.out.println("每隔5秒执行一次 "+dateFormat.format(new Date()));
    }
 
    @Scheduled(cron = "0 07 20 ? * *" ) //使用cron属性可按照指定时间执行,本例指的是每天20点07分执行;
    //cron是UNIX和类UNIX(Linux)系统下的定时任务
    public void fixTimeExecution(){
        System.out.println("在指定时间 "+dateFormat.format(new Date())+" 执行");
    }
}

//配置类
@Configuration
@ComponentScan("")
@EnableScheduling //通过@EnableScheduling注解开启对计划任务的支持
public class TaskScheduleConfig {
}

持续更新~