spring之order注解
- 2019 年 11 月 26 日
- 筆記
我们今天要分享的是spring框架提供的@Order注解的使用,估计这篇文章的阅读时间应该在二到三分钟之间就结束了。
好了,其实这个注解还是蛮常用的,可以控制加载的顺序,仅此而已。下面我们还是按照往日的风格进行写吧,我们先看下我们的示例程序。
package com.wpw.dockerspringboot; public class Student { }
package com.wpw.dockerspringboot; public class Student2 { }
上面就是简单的定义两个java类,什么都不做,为下面需要写的配置类做下铺垫而已。
package com.wpw.dockerspringboot; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; @Order(value=1)//这里指定order的值为1 @Configuration public class Configuration1 { @Bean public Student getStudent(){ System.out.println("configuration1被加载"); return new Student(); } }
上面我们定义了一个配置类,里面可以获取Student类的示例,顺便打印出了一句表示加载顺序的。
package com.wpw.dockerspringboot; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; @Order(value=2)//这里设置order的值为2 @Configuration public class Configuration2 { @Bean public Student2 getStudent2(){ System.out.println("configuration2被加载了"); return new Student2(); } }
上面同样定义了一个配置类,主要是为了获取Student2类的实例,顺便打印了一下加载的顺序。
ok,到这里我们只需要启动下面的主程序。
package com.wpw.dockerspringboot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DockerSpringbootApplication { public static void main(String[] args) { SpringApplication.run(DockerSpringbootApplication.class, args); } }
我们看下控制台的输出语句就应该学会了spring提供的order注解的使用了。
2019-11-10 18:33:53.033 INFO 3136 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1383 ms configuration1被加载 configuration2被加载了 2019-11-10 18:33:53.211 INFO 3136 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'