一、@Order
注解@Order的作用是定义Spring容器加载Bean的顺序
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
@Documented
public @interface Order {
/**
* 默认最低优先级
*/
int value() default Ordered.LOWEST_PRECEDENCE;
}
二、@Order使用
简单使用一下@Order测试效果
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(1)
public class ComponentOne{
ComponentOne(){
System.out.println("Component One");
}
}
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(2)
public class ComponentTwo{
ComponentTwo(){
System.out.println("Component Two");
}
}
@Component
@Order(3)
public class ComponentThree{
ComponentThree(){
System.out.println("Component Three");
}
}
项目启动后执行结果:
Component One
Component Three
Component Two
@Order没生效、还是默认的加载顺序、原因还需研究
三、实现CommandLineRunner接口
实现CommandLineRunner接口,在项目启动后执行,实现功能的代码放在实现的run方法中。
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(1)
public class ComponentOne implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("Component One");
}
}
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(2)
public class ComponentTwo implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("Component Two");
}
}
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(3)
public class ComponentThree implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("Component Three");
}
}
项目启动后执行结果:
Component One
Component Two
Component Three
@Order根据顺序生效
关于@Order还有问题需要研究
本文介绍了Spring框架中的@Order注解,用于定义Bean加载的顺序。通过一个简单的测试示例展示了@Order的使用,但在初始尝试中并未按预期生效。接着,文章提到了实现CommandLineRunner接口来在项目启动后执行特定代码,此时@Order注解的顺序作用得以体现,但同时也指出@Order注解的深入理解仍有待研究。
647

被折叠的 条评论
为什么被折叠?



