版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Thinkingcao/article/details/84801093
1 、@Order
1、Spring 4.2 利用@Order
控制配置类的加载顺序,
2、Spring在加载Bean的时候,有用到order注解。
3、通过@Order
指定执行顺序,值越小,越先执行
4、@Order注解常用于定义的AOP先于事物执行
2 、新建Springboot项目来测试
(1)、引入依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
(2)、新建3个Order0Config、Order1Config、Order2Config和3个Order0Service、Order1Service、Order2Service
Order0Config示例代码:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import com.thinkingcao.modules.service.Order0Service;
/**
* <pre>
* @author cao_wencao
* @date 2018年12月4日 下午10:59:05
* </pre>
*/
@Configuration
@Order(0)
public class Order0Config {
@Bean
public Order0Service order0Service(){
System.out.println("Order0Config 加载了");
return new Order0Service();
}
}
Order1Config示例代码:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import com.thinkingcao.modules.service.Order1Service;
/**
* <pre>
* @author cao_wencao
* @date 2018年12月4日 下午10:57:41
* </pre>
*/
@Configuration
@Order(1)
public class Order1Config {
@Bean
public Order1Service order1Service(){
System.out.println("Order1Config 加载了");
return new Order1Service();
}
}
Order2Config示例代码
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import com.thinkingcao.modules.service.Order2Service;
/**
* <pre>
* @author cao_wencao
* @date 2018年12月4日 下午10:58:49
* </pre>
*/
@Configuration
@Order(2)
public class Order2Config {
@Bean
public Order2Service order2Service(){
System.out.println("Order2Config 加载了");
return new Order2Service();
}
}
(3)、运行测试类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* <pre>
* @author cao_wencao
* @date 2018年12月4日 下午11:53:43
* </pre>
*/
@SpringBootApplication
public class Application {
/**
* <pre>
* @author cao_wencao
* @param args
* </pre>
*/
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
效果图:
总结 :
默认情况下@订单注释遵循从低到高的顺序,即最低值具有高优先级。 这意味着它们首先出现在列表或数组中。 因为默认情况下,排序优先级设置为Ordered.LOWEST_PRECEDENCE。 如果您首先需要最高值,那么我们需要将此值更改为Ordered.HIGHEST_PRECEDENCE。