使用@Order註解調整配置類載入順序
阿新 • • 發佈:2018-12-05
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。