How to control the initialization order of Bean in Spring interview questions

Question: How to control the order of Bean initialization in Spring?

Since the emergence of Spring 2.0, Spring provides @Order annotations to define the loading order of components.

@Order definition

@Retention(value=RUNTIME)@Target(value={TYPE,METHOD,FIELD})@Documented public @interface Order

This tag contains a value attribute, the type is integer, such as: 1, 2, etc. The smaller the value, the higher the priority.

The default attribute is Ordered.LOWEST_PRECEDENCE,

Represents the lowest priority.

It can be found through the code that the definitions of the maximum and minimum values ​​are the maximum and minimum values ​​of Inger.

How to control the initialization order of Bean in Spring interview questions

Simple example

Ranks.java

How to control the initialization order of Bean in Spring interview questions

RankOne.java

How to control the initialization order of Bean in Spring interview questions

RankTwo.java

How to control the initialization order of Bean in Spring interview questions

RankThree.java

How to control the initialization order of Bean in Spring interview questions

Results.java

How to control the initialization order of Bean in Spring interview questions

beans.xml

How to control the initialization order of Bean in Spring interview questions

RanksClient.java

How to control the initialization order of Bean in Spring interview questions

Run output:

[RankOne, RankThree, RankTwo]

Modify the RankTwo code:

@Component@Order(1)

public  class  RankTwo  implements  Ranks{ //Same code as given above}

Run output:

[RankTwo, RankOne, RankThree]

Guess you like

Origin blog.csdn.net/keepfriend/article/details/113860086