2015-05-19 64 views
29

我曾經看過使用@Order註釋的代碼。我想知道這個註釋在Spring Security或Spring MVC中的用法。Spring中@Order註釋的用途是什麼?

下面是一個例子:

@Order(1) 
public class StatelessAuthenticationSecurityConfig extends WebSecurityConfigurerAdapter { 

    @Autowired 
    private UserDetailsService userDetailsService; 

    @Autowired 
    private TokenAuthenticationService tokenAuthenticationService; 

} 

什麼發生上述類的順序,如果我們不使用此批註?

+2

http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/annotation/Order.html。有關Spring Security的 –

+0

,這可以例如定義應用安全過濾器的順序 –

回答

40

它用於建議執行優先級。

最高優先級建議先運行。數字越小,優先級越高。例如,給定兩條'之前'的建議,優先級最高的將首先運行。

使用它的另一種方式是訂購自動裝配Autowired收藏

@Component 
@Order(2) 
class Toyota extends Car { 
    public String getName() { 
     return "Toyota"; 
    } 
} 

@Component 
@Order(1) 
class Mazda extends Car { 
    public String getName() { 
     return "Mazda"; 
    } 
} 

@Component 
public class Cars { 
    @Autowire 
    List<Car> cars; 

    public void printNames(String [] args) { 

     for(Car car : cars) { 
      System.out.println(car.getName()) 
     } 
    } 
} 

你可以找到可執行代碼在這裏:https://github.com/patrikbego/spring-order-demo.git

希望這闡明它遠一點。

+3

將很明顯,如果你已經把這個程序的輸出 – thiagoh

+5

輸出是:馬自達 豐田:) –

+0

這可以用來指定不同的bean應該被銷燬的順序? –

3

@Order註解(以及Ordered接口)意味着一個特定的順序,在這個順序中,Spring將加載或優先安排bean。

數字越小表示優先級越高。該功能可用於將Bean以特定順序添加到集合中(即通過@Autowired)等等。

在您的具體示例中,註釋不會更改類本身中的任何內容。無論使用哪個特定的類,它都以最高的優先級使用(因爲它被設置爲'1'),可能是因爲額外的但依賴的信息正在被添加到其他類中,以較低的優先級排序。

相關問題