• spring中那些让你爱不释手的代码技巧(续集)


    一. @Conditional的强大之处

    不知道你们有没有遇到过这些问题:

    1. 某个功能需要根据项目中有没有某个jar判断是否开启该功能。

    2. 某个bean的实例化需要先判断另一个bean有没有实例化,再判断是否实例化自己。

    3. 某个功能是否开启,在配置文件中有个参数可以对它进行控制。

    如果你有遇到过上述这些问题,那么恭喜你,本节内容非常适合你。

    @ConditionalOnClass

    问题1可以用@ConditionalOnClass注解解决,代码如下:

    1. public class A {
    2. }
    3. public class B {
    4. }
    5. @ConditionalOnClass(B.class)
    6. @Configuration
    7. public class TestConfiguration {
    8. @Bean
    9. public A a() {
    10. return new A();
    11. }
    12. }

    如果项目中存在B类,则会实例化A类。如果不存在B类,则不会实例化A类。

    有人可能会问:不是判断有没有某个jar吗?怎么现在判断某个类了?

    直接判断有没有该jar下的某个关键类更简单。

    这个注解有个升级版的应用场景:比如common工程中写了一个发消息的工具类mqTemplate,业务工程引用了common工程,只需再引入消息中间件,比如rocketmq的jar包,就能开启mqTemplate的功能。而如果有另一个业务工程,通用引用了common工程,如果不需要发消息的功能,不引入rocketmq的jar包即可。

    这个注解的功能还是挺实用的吧?

    @ConditionalOnBean

    问题2可以通过@ConditionalOnBean注解解决,代码如下:

    1. @Configuration
    2. public class TestConfiguration {
    3. @Bean
    4. public B b() {
    5. return new B();
    6. }
    7. @ConditionalOnBean(name="b")
    8. @Bean
    9. public A a() {
    10. return new A();
    11. }
    12. }

    实例A只有在实例B存在时,才能实例化。

    @ConditionalOnProperty

    问题3可以通过@ConditionalOnProperty注解解决,代码如下:

    1. @ConditionalOnProperty(prefix = "demo",name="enable", havingValue = "true",matchIfMissing=true )
    2. @Configuration
    3. public class TestConfiguration {
    4. @Bean
    5. public A a() {
    6. return new A();
    7. }
    8. }

    在applicationContext.properties文件中配置参数:

    demo.enable=false
    

    各参数含义:

    • prefix 表示参数名的前缀,这里是demo

    • name 表示参数名

    • havingValue 表示指定的值,参数中配置的值需要跟指定的值比较是否相等,相等才满足条件

    • matchIfMissing 表示是否允许缺省配置。

    这个功能可以作为开关,相比EnableXXX注解的开关更优雅,因为它可以通过参数配置是否开启,而EnableXXX注解的开关需要在代码中硬编码开启或关闭。

    其他的Conditional注解

    当然,spring用得比较多的Conditional注解还有:ConditionalOnMissingClassConditionalOnMissingBeanConditionalOnWebApplication等。

    下面用一张图整体认识一下@Conditional家族。

    a72afbe589494b19b788fb03f7e7ec26.png  

    自定义Conditional

    说实话,个人认为springboot自带的Conditional系列已经可以满足我们绝大多数的需求了。但如果你有比较特殊的场景,也可以自定义自定义Conditional。

    第一步,自定义注解:

    1. @Conditional(MyCondition.class)
    2. @Retention(RetentionPolicy.RUNTIME)
    3. @Target({ElementType.TYPE, ElementType.METHOD})
    4. @Documented
    5. public @interface MyConditionOnProperty {
    6. String name() default "";
    7. String havingValue() default "";
    8. }

    第二步,实现Condition接口:

    1. public class MyCondition implements Condition {
    2. @Override
    3. public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    4. System.out.println("实现自定义逻辑");
    5. return false;
    6. }
    7. }

    第三步,使用@MyConditionOnProperty注解。

    Conditional的奥秘就藏在ConfigurationClassParser类的processConfigurationClass方法中:

    69ec084593564756bdb5079d199193cd.png 

    这个方法逻辑不复杂:

    6fd07a1320c749748439022b242dbead.png 

    1. 先判断有没有使用Conditional注解,如果没有直接返回false

    2. 收集condition到集合中

    3. order排序该集合

    4. 遍历该集合,循环调用conditionmatchs方法。

    二. 如何妙用@Import?

    有时我们需要在某个配置类中引入另外一些类,被引入的类也加到spring容器中。这时可以使用@Import注解完成这个功能。

    如果你看过它的源码会发现,引入的类支持三种不同类型。

    但是我认为最好将普通类和@Configuration注解的配置类分开讲解,所以列了四种不同类型:

    559dbad04d134cf08dd4b41f82e51c7d.png 

    普通类

    这种引入方式是最简单的,被引入的类会被实例化bean对象。

    1. public class A {
    2. }
    3. @Import(A.class)
    4. @Configuration
    5. public class TestConfiguration {
    6. }

    通过@Import注解引入A类,spring就能自动实例化A对象,然后在需要使用的地方通过@Autowired注解注入即可:

    1. @Autowired
    2. private A a;

    是不是挺让人意外的?不用加@Bean注解也能实例化bean。

    @Configuration注解的配置类

    这种引入方式是最复杂的,因为@Configuration注解还支持多种组合注解,比如:

    • @Import

    • @ImportResource

    • @PropertySource等。

    1. public class A {
    2. }
    3. public class B {
    4. }
    5. @Import(B.class)
    6. @Configuration
    7. public class AConfiguration {
    8. @Bean
    9. public A a() {
    10. return new A();
    11. }
    12. }
    13. @Import(AConfiguration.class)
    14. @Configuration
    15. public class TestConfiguration {
    16. }

    通过@Import注解引入@Configuration注解的配置类,会把该配置类相关@Import@ImportResource@PropertySource等注解引入的类进行递归,一次性全部引入。

    由于文章篇幅有限不过多介绍了,这里留点悬念,后面会出一篇文章专门介绍@Configuration注解,因为它实在太太太重要了。

    实现ImportSelector接口的类

    这种引入方式需要实现ImportSelector接口:

    1. public class AImportSelector implements ImportSelector {
    2. private static final String CLASS_NAME = "com.sue.cache.service.test13.A";
    3. public String[] selectImports(AnnotationMetadata importingClassMetadata) {
    4. return new String[]{CLASS_NAME};
    5. }
    6. }
    7. @Import(AImportSelector.class)
    8. @Configuration
    9. public class TestConfiguration {
    10. }

    这种方式的好处是selectImports方法返回的是数组,意味着可以同时引入多个类,还是非常方便的。

    实现ImportBeanDefinitionRegistrar接口的类

    这种引入方式需要实现ImportBeanDefinitionRegistrar接口:

    1. public class AImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
    2. @Override
    3. public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
    4. RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(A.class);
    5. registry.registerBeanDefinition("a", rootBeanDefinition);
    6. }
    7. }
    8. @Import(AImportBeanDefinitionRegistrar.class)
    9. @Configuration
    10. public class TestConfiguration {
    11. }

    这种方式是最灵活的,能在registerBeanDefinitions方法中获取到BeanDefinitionRegistry容器注册对象,可以手动控制BeanDefinition的创建和注册。

    当然@import注解非常人性化,还支持同时引入多种不同类型的类。

    1. @Import({B.class,AImportBeanDefinitionRegistrar.class})
    2. @Configuration
    3. public class TestConfiguration {
    4. }

    这四种引入类的方式各有千秋,总结如下:

    1. 普通类,用于创建没有特殊要求的bean实例。

    2. @Configuration注解的配置类,用于层层嵌套引入的场景。

    3. 实现ImportSelector接口的类,用于一次性引入多个类的场景,或者可以根据不同的配置决定引入不同类的场景。

    4. 实现ImportBeanDefinitionRegistrar接口的类,主要用于可以手动控制BeanDefinition的创建和注册的场景,它的方法中可以获取BeanDefinitionRegistry注册容器对象。

    ConfigurationClassParser类的processImports方法中可以看到这三种方式的处理逻辑:

    aa4467d668b049049a628d1e1b2c7570.png 

    最后的else方法其实包含了:普通类和@Configuration注解的配置类两种不同的处理逻辑。

    三. @ConfigurationProperties赋值

    我们在项目中使用配置参数是非常常见的场景,比如,我们在配置线程池的时候,需要在applicationContext.propeties文件中定义如下配置:

    1. thread.pool.corePoolSize=5
    2. thread.pool.maxPoolSize=10
    3. thread.pool.queueCapacity=200
    4. thread.pool.keepAliveSeconds=30

    方法一:通过@Value注解读取这些配置。

    1. public class ThreadPoolConfig {
    2. @Value("${thread.pool.corePoolSize:5}")
    3. private int corePoolSize;
    4. @Value("${thread.pool.maxPoolSize:10}")
    5. private int maxPoolSize;
    6. @Value("${thread.pool.queueCapacity:200}")
    7. private int queueCapacity;
    8. @Value("${thread.pool.keepAliveSeconds:30}")
    9. private int keepAliveSeconds;
    10. @Value("${thread.pool.threadNamePrefix:ASYNC_}")
    11. private String threadNamePrefix;
    12. @Bean
    13. public Executor threadPoolExecutor() {
    14. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    15. executor.setCorePoolSize(corePoolSize);
    16. executor.setMaxPoolSize(maxPoolSize);
    17. executor.setQueueCapacity(queueCapacity);
    18. executor.setKeepAliveSeconds(keepAliveSeconds);
    19. executor.setThreadNamePrefix(threadNamePrefix);
    20. executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    21. executor.initialize();
    22. return executor;
    23. }
    24. }

    这种方式使用起来非常简单,但建议在使用时都加上:,因为:后面跟的是默认值,比如:@Value("${thread.pool.corePoolSize:5}"),定义的默认核心线程数是5。

    假如有这样的场景:business工程下定义了这个ThreadPoolConfig类,api工程引用了business工程,同时job工程也引用了business工程,而ThreadPoolConfig类只想在api工程中使用。这时,如果不配置默认值,job工程启动的时候可能会报错。

    如果参数少还好,多的话,需要给每一个参数都加上@Value注解,是不是有点麻烦?

    此外,还有一个问题,@Value注解定义的参数看起来有点分散,不容易辨别哪些参数是一组的。

    这时,@ConfigurationProperties就派上用场了,它是springboot中新加的注解。

    第一步,先定义ThreadPoolProperties类

    1. @Data
    2. @Component
    3. @ConfigurationProperties("thread.pool")
    4. public class ThreadPoolProperties {
    5. private int corePoolSize;
    6. private int maxPoolSize;
    7. private int queueCapacity;
    8. private int keepAliveSeconds;
    9. private String threadNamePrefix;
    10. }

    第二步,使用ThreadPoolProperties类

    1. @Configuration
    2. public class ThreadPoolConfig {
    3. @Autowired
    4. private ThreadPoolProperties threadPoolProperties;
    5. @Bean
    6. public Executor threadPoolExecutor() {
    7. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    8. executor.setCorePoolSize(threadPoolProperties.getCorePoolSize());
    9. executor.setMaxPoolSize(threadPoolProperties.getMaxPoolSize());
    10. executor.setQueueCapacity(threadPoolProperties.getQueueCapacity());
    11. executor.setKeepAliveSeconds(threadPoolProperties.getKeepAliveSeconds());
    12. executor.setThreadNamePrefix(threadPoolProperties.getThreadNamePrefix());
    13. executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    14. executor.initialize();
    15. return executor;
    16. }
    17. }

    使用@ConfigurationProperties注解,可以将thread.pool开头的参数直接赋值到ThreadPoolProperties类的同名参数中,这样省去了像@Value注解那样一个个手动去对应的过程。

    这种方式显然要方便很多,我们只需编写xxxProperties类,spring会自动装配参数。此外,不同系列的参数可以定义不同的xxxProperties类,也便于管理,推荐优先使用这种方式。

    它的底层是通过:ConfigurationPropertiesBindingPostProcessor类实现的,该类实现了BeanPostProcessor接口,在postProcessBeforeInitialization方法中解析@ConfigurationProperties注解,并且绑定数据到相应的对象上。

    绑定是通过Binder类的bindObject方法完成的:

    ccf12e6489114c9ea5f8e1c77303bcb1.png 

    以上这段代码会递归绑定数据,主要考虑了三种情况:

    • bindAggregate 绑定集合类

    • bindBean 绑定对象

    • bindProperty 绑定参数 前面两种情况最终也会调用到bindProperty方法。

    「此外,友情提醒一下:」

    使用@ConfigurationProperties注解有些场景有问题,比如:在apollo中修改了某个参数,正常情况可以动态更新到@ConfigurationProperties注解定义的xxxProperties类的对象中,但是如果出现比较复杂的对象,比如:

    private Map<String, Map<String,String>>  urls;
    

    可能动态更新不了。

    这时候该怎么办呢?

    答案是使用ApolloConfigChangeListener监听器自己处理:

    1. @ConditionalOnClass(com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig.class)
    2. public class ApolloConfigurationAutoRefresh implements ApplicationContextAware {
    3. private ApplicationContext applicationContext;
    4. @Override
    5. public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    6. this.applicationContext = applicationContext;
    7. }
    8. @ApolloConfigChangeListener
    9. private void onChange(ConfigChangeEvent changeEvent{
    10. refreshConfig(changeEvent.changedKeys());
    11. }
    12. private void refreshConfig(Set changedKeys){
    13. System.out.println("将变更的参数更新到相应的对象中");
    14. }
    15. }

    四. spring事务要如何避坑?

    spring中的事务功能主要分为:声明式事务编程式事务

    声明式事务

    大多数情况下,我们在开发过程中使用更多的可能是声明式事务,即使用@Transactional注解定义的事务,因为它用起来更简单,方便。

    只需在需要执行的事务方法上,加上@Transactional注解就能自动开启事务:

    1. @Service
    2. public class UserService {
    3. @Autowired
    4. private UserMapper userMapper;
    5. @Transactional
    6. public void add(UserModel userModel) {
    7. userMapper.insertUser(userModel);
    8. }
    9. }

    这种声明式事务之所以能生效,是因为它的底层使用了AOP,创建了代理对象,调用TransactionInterceptor拦截器实现事务的功能。

    spring事务有个特别的地方:它获取的数据库连接放在ThreadLocal中的,也就是说同一个线程中从始至终都能获取同一个数据库连接,可以保证同一个线程中多次数据库操作在同一个事务中执行。

    正常情况下是没有问题的,但是如果使用不当,事务会失效,主要原因如下:

    45421b288cac4128afd170975405fa2a.png 

    除了上述列举的问题之外,由于@Transactional注解最小粒度是要被定义在方法上,如果有多层的事务方法调用,可能会造成大事务问题。

    9ac4a3eda88344d1b2bc113150fabcbc.png 

    所以,建议在实际工作中少用@Transactional注解开启事务。

    编程式事务

    一般情况下编程式事务我们可以通过TransactionTemplate类开启事务功能。有个好消息,就是springboot已经默认实例化好这个对象了,我们能直接在项目中使用。

    1. @Service
    2. public class UserService {
    3. @Autowired
    4. private TransactionTemplate transactionTemplate;
    5. ...
    6. public void save(final User user) {
    7. transactionTemplate.execute((status) => {
    8. doSameThing...
    9. return Boolean.TRUE;
    10. })
    11. }
    12. }

    使用TransactionTemplate的编程式事务能避免很多事务失效的问题,但是对大事务问题,不一定能够解决,只是说相对于使用@Transactional注解要好些。

    五. 跨域问题的解决方案

    关于跨域问题,前后端的解决方案还是挺多的,这里我重点说说spring的解决方案,目前有三种:

    768682e34128496db87d66dd421ff4ef.png 

    一.使用@CrossOrigin注解

    1. @RequestMapping("/user")
    2. @RestController
    3. public class UserController {
    4. @CrossOrigin(origins = "http://localhost:8016")
    5. @RequestMapping("/getUser")
    6. public String getUser(@RequestParam("name") String name) {
    7. System.out.println("name:" + name);
    8. return "success";
    9. }
    10. }

    该方案需要在跨域访问的接口上加@CrossOrigin注解,访问规则可以通过注解中的参数控制,控制粒度更细。如果需要跨域访问的接口数量较少,可以使用该方案。

    二.增加全局配置

    1. @Configuration
    2. public class WebConfig implements WebMvcConfigurer {
    3. @Override
    4. public void addCorsMappings(CorsRegistry registry) {
    5. registry.addMapping("/**")
    6. .allowedOrigins("*")
    7. .allowedMethods("GET", "POST")
    8. .allowCredentials(true)
    9. .maxAge(3600)
    10. .allowedHeaders("*");
    11. }
    12. }

    该方案需要实现WebMvcConfigurer接口,重写addCorsMappings方法,在该方法中定义跨域访问的规则。这是一个全局的配置,可以应用于所有接口。

    三.自定义过滤器

    1. @WebFilter("corsFilter")
    2. @Configuration
    3. public class CorsFilter implements Filter {
    4. @Override
    5. public void init(FilterConfig filterConfig) throws ServletException {
    6. }
    7. @Override
    8. public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    9. HttpServletResponse httpServletResponse = (HttpServletResponse) response;
    10. httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
    11. httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET");
    12. httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
    13. httpServletResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with");
    14. chain.doFilter(request, response);
    15. }
    16. @Override
    17. public void destroy() {
    18. }
    19. }

    该方案通过在请求的header中增加Access-Control-Allow-Origin等参数解决跨域问题。

    顺便说一下,使用@CrossOrigin注解 和 实现WebMvcConfigurer接口的方案,spring在底层最终都会调用到DefaultCorsProcessor类的handleInternal方法:

    97327afb273a422bb602808c36ef6a86.png 

    最终三种方案殊途同归,都会往header中添加跨域需要参数,只是实现形式不一样而已。

    六. 如何自定义starter

    以前在没有使用starter时,我们在项目中需要引入新功能,步骤一般是这样的:

    • 在maven仓库找该功能所需jar包

    • 在maven仓库找该jar所依赖的其他jar包

    • 配置新功能所需参数

    以上这种方式会带来三个问题:

    1. 如果依赖包较多,找起来很麻烦,容易找错,而且要花很多时间。

    2. 各依赖包之间可能会存在版本兼容性问题,项目引入这些jar包后,可能没法正常启动。

    3. 如果有些参数没有配好,启动服务也会报错,没有默认配置。

    「为了解决这些问题,springboot的starter机制应运而生」

    starter机制带来这些好处:

    1. 它能启动相应的默认配置。

    2. 它能够管理所需依赖,摆脱了需要到处找依赖 和 兼容性问题的困扰。

    3. 自动发现机制,将spring.factories文件中配置的类,自动注入到spring容器中。

    4. 遵循“约定大于配置”的理念。

    在业务工程中只需引入starter包,就能使用它的功能,太爽了。

    下面用一张图,总结starter的几个要素:

    8c7963cfe427454a8b410f52fff2fec2.png 

    接下来我们一起实战,定义一个自己的starter。

    第一步,创建id-generate-starter工程:

    a186f4d232284df5a6053cea30fc88c7.png 

    其中的pom.xml配置如下:

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    3. <modelVersion>4.0.0</modelVersion>
    4. <version>1.3.1</version>
    5. <groupId>com.sue</groupId>
    6. <artifactId>id-generate-spring-boot-starter</artifactId>
    7. <name>id-generate-spring-boot-starter</name>
    8. <dependencies>
    9. <dependency>
    10. <groupId>com.sue</groupId>
    11. <artifactId>id-generate-spring-boot-autoconfigure</artifactId>
    12. <version>1.3.1</version>
    13. </dependency>
    14. </dependencies>
    15. </project>

    第二步,创建id-generate-spring-boot-autoconfigure工程:

    4485c8533feb439badc337f028f49a60.png 

    该项目当中包含:

    • pom.xml

    • spring.factories

    • IdGenerateAutoConfiguration

    • IdGenerateService

    • IdProperties pom.xml配置如下:

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    3. <parent>
    4. <groupId>org.springframework.boot</groupId>
    5. <artifactId>spring-boot-starter-parent</artifactId>
    6. <version>2.0.4.RELEASE</version>
    7. </parent>
    8. <modelVersion>4.0.0</modelVersion>
    9. <version>1.3.1</version>
    10. <groupId>com.sue</groupId>
    11. <artifactId>id-generate-spring-boot-autoconfigure</artifactId>
    12. <name>id-generate-spring-boot-autoconfigure</name>
    13. <dependencies>
    14. <dependency>
    15. <groupId>org.springframework.boot</groupId>
    16. <artifactId>spring-boot-starter</artifactId>
    17. </dependency>
    18. <dependency>
    19. <groupId>org.springframework.boot</groupId>
    20. <artifactId>spring-boot-autoconfigure</artifactId>
    21. </dependency>
    22. <dependency>
    23. <groupId>org.springframework.boot</groupId>
    24. <artifactId>spring-boot-configuration-processor</artifactId>
    25. <optional>true</optional>
    26. </dependency>
    27. </dependencies>
    28. <build>
    29. <plugins>
    30. <plugin>
    31. <groupId>org.apache.maven.plugins</groupId>
    32. <artifactId>maven-compiler-plugin</artifactId>
    33. <configuration>
    34. <source>1.8</source>
    35. <target>1.8</target>
    36. </configuration>
    37. </plugin>
    38. </plugins>
    39. </build>
    40. </project>

    spring.factories配置如下:

    1. org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.sue.IdGenerateAutoConfiguration

    IdGenerateAutoConfiguration类:

    1. @ConditionalOnClass(IdProperties.class)
    2. @EnableConfigurationProperties(IdProperties.class)
    3. @Configuration
    4. public class IdGenerateAutoConfiguration {
    5. @Autowired
    6. private IdProperties properties;
    7. @Bean
    8. public IdGenerateService idGenerateService() {
    9. return new IdGenerateService(properties.getWorkId());
    10. }
    11. }

    IdGenerateService类:

    1. public class IdGenerateService {
    2. private Long workId;
    3. public IdGenerateService(Long workId) {
    4. this.workId = workId;
    5. }
    6. public Long generate() {
    7. return new Random().nextInt(100) + this.workId;
    8. }
    9. }

    IdProperties类:

    1. @ConfigurationProperties(prefix = IdProperties.PREFIX)
    2. public class IdProperties {
    3. public static final String PREFIX = "sue";
    4. private Long workId;
    5. public Long getWorkId() {
    6. return workId;
    7. }
    8. public void setWorkId(Long workId) {
    9. this.workId = workId;
    10. }
    11. }

    这样在业务项目中引入相关依赖:

    1. <dependency>
    2. <groupId>com.sue</groupId>
    3. <artifactId>id-generate-spring-boot-starter</artifactId>
    4. <version>1.3.1</version>
    5. </dependency>

    就能使用注入使用IdGenerateService的功能了

    1. @Autowired
    2. private IdGenerateService idGenerateService;

    完美。

    七.项目启动时的附加功能

    有时候我们需要在项目启动时定制化一些附加功能,比如:加载一些系统参数、完成初始化、预热本地缓存等,该怎么办呢?

    好消息是springboot提供了:

    • CommandLineRunner

    • ApplicationRunner

    这两个接口帮助我们实现以上需求。

    它们的用法还是挺简单的,以ApplicationRunner接口为例:

    1. @Component
    2. public class TestRunner implements ApplicationRunner {
    3. @Autowired
    4. private LoadDataService loadDataService;
    5. public void run(ApplicationArguments args) throws Exception {
    6. loadDataService.load();
    7. }
    8. }

    实现ApplicationRunner接口,重写run方法,在该方法中实现自己定制化需求。

    如果项目中有多个类实现了ApplicationRunner接口,他们的执行顺序要怎么指定呢?

    答案是使用@Order(n)注解,n的值越小越先执行。当然也可以通过@Priority注解指定顺序。

    springboot项目启动时主要流程是这样的:

    a4bc7a6cb29945f8a6761777053959a7.png 

    SpringApplication类的callRunners方法中,我们能看到这两个接口的具体调用:

    8033dec4b1ed46998f1e12c3f0bbd936.png 

    最后还有一个问题:这两个接口有什么区别?

    • CommandLineRunner接口中run方法的参数为String数组

    • ApplicationRunner中run方法的参数为ApplicationArguments,该参数包含了String数组参数 和 一些可选参数。

    唠唠家常

    写着写着又有这么多字了,按照惯例,为了避免篇幅过长,今天就先写到这里。预告一下,后面会有AOP、BeanPostProcessor、Configuration注解等核心知识点的专题,每个主题的内容都挺多的,可以期待一下喔。

    最后说一句(求关注,别白嫖我)

    如果这篇文章对您有所帮助,或者有所启发的话,帮忙扫描下发二维码关注一下,您的支持是我坚持写作最大的动力。

     

  • 相关阅读:
    【USRP】软件无线电基础篇:长波、中波、短波
    背完这套 Java 面试八股文,自动解锁面试牛逼症被动技能
    使用Docker本地安装部署Drawio绘图工具并实现公网访问
    GIT中对子仓库的使用方法介绍
    JAVA计算机毕业设计衣依服装销售平台Mybatis+系统+数据库+调试部署
    JAVA-SpelExpressionParser公式运算表达式的使用
    Springboot企业差旅报销系统_5h38k计算机毕业设计-课程设计-期末作业-毕设程序代做
    Java封装之this关键字、static关键字、包简述
    Java 和 JavaScript 有什么区别?
    ROS2时间同步(python)
  • 原文地址:https://blog.csdn.net/m0_72088858/article/details/126746924