https://www.dazhuanlan.com/2019/10/22/5daebc5d16429/
最近在做傳統Spring項目到SpringBoot項目遷移過程中,遇到了一些bean加載順序的問題:
比如一個config中的bean依賴於另一個config中的bean進行初始化,於是查了一些資料,出現了一些新的概念:
@Order
@AutoConfigureAfter
@DependsOn
@Order
注解
Before Spring 4.0, the
@Order
annotation was used only for theAspectJ
execution order. It means the highest order advice will run first.
Since Spring 4.0, it supports the ordering of injected components to a collection. As a result, Spring will inject the auto-wired beans of the same type based on their order value.
在Spring 4.0版本之前,@Order
注解只能控制AOP的執行順序,在Spring 4.0之后,它還可以控制集合注入中bean的順序。
控制AOP順序很好理解,例如可以在@Aspect
注解的切面上加入@Order
注解,控制切面的執行順序。
還有@EnableTransactionManagement(order = 10)
,這種寫法,由於Spring的事務也是用AOP實現,也可以控制優先級。
下面舉個例子說明控制集合注入中bean的順序。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
public interface {
int getRating();
}
public class Excellent implements {
public int getRating() {
return 1;
}
}
public class Good implements {
public int getRating() {
return 2;
}
}
public class Average implements {
public int getRating() {
return 3;
}
}
|
最后是測試類:
1
2
3
4
5
6
7
8
9
10
11
12
|
public class RatingRetrieverUnitTest {
private List<Rating> ratings;
public void givenOrder_whenInjected_thenByOrderValue() {
assertThat(ratings.get(
0).getRating(), is(equalTo(1)));
assertThat(ratings.get(
1).getRating(), is(equalTo(2)));
assertThat(ratings.get(
2).getRating(), is(equalTo(3)));
}
}
|
如果不使用@Order
注解,那ratings集合可能是亂序的。
有一種錯誤的用法:
先定義兩個service:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
public class OrderService1 {
private static final Logger LOGGER = LoggerFactory.getLogger(OrderService1.class);
public OrderService1() {
LOGGER.info(
"OrderService1 constructor");
}
public String name() {
return "orderService1";
}
}
public class OrderService2 {
private static final Logger LOGGER = LoggerFactory.getLogger(OrderService2.class);
public OrderService2() {
LOGGER.info(
"OrderService2 constructor");
}
public String name() {
return "orderService2";
}
}
|
然后寫兩個config注入bean:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
public class OrderService1Config {
private static final Logger LOGGER = LoggerFactory.getLogger(OrderService1Config.class);
public OrderService1 orderService1() {
LOGGER.info(
"orderService1 init");
return new OrderService1();
}
}
public class OrderService2Config {
private static final Logger LOGGER = LoggerFactory.getLogger(OrderService2Config.class);
public OrderService2 orderService2() {
LOGGER.info(
"orderService2 init");
return new OrderService2();
}
}
|
本意是想通過@Order
控制bean的注入順序,先注入orderService2,再注入orderService1。但是並沒有效果。
所以,@Order
注解放到@Configuration
中是無法控制bean的注入順序的。
@AutoConfigureAfter
注解
Hint for that an
EnableAutoConfiguration
auto-configuration should be applied after other specified auto-configuration classes.
類似的注解還有:
@AutoConfigureBefore
@AutoConfigureOrder
這三個注解是特地用於autoconfigure類的,不能用於普通的配置類。
有必要先說明一下autoconfigure類項目。
通常我們會在主類入口上標注@SpringBootApplication
注解,或者直接標注@EnableAutoConfiguration
注解。
這個注解是用來根據類路徑中的依賴包猜測需要注入的bean,實現自動注入:
Enable auto-configuration of the Spring Application Context, attempting to guess and configure beans that you are likely to need. Auto-configuration classes are usually applied based on your classpath and what beans you have defined.
可以理解為,@EnableAutoConfiguration
是服務於自動注入的bean的,即spring-boot-starter
中bean的自動加載順序。
被排序的這些類,都是通過xxx-spring-boot-autoconfigure
項目中的src/resources/META-INF/spring.factories
配置文件獲取的,這個文件中的配置內容一般為:
1
2
3
|
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=
com.github.pagehelper.autoconfigure.PageHelperAutoConfiguration
|
Spring Boot 只會對從這個文件讀取的配置類進行排序。
但是不要以為將自己的配置類也配置在spring.factories
中就能實現排序,如果你的類被自己Spring Boot
啟動類掃描到了,這個類的順序會優先於所有通過spring.factories
讀取的配置類。
Auto-configuration is always applied after user-defined beans have been registered.
@DependsOn
注解
Beans on which the current bean depends. Any beans specified are guaranteed to be created by the container before this bean.
Used infrequently in cases where a bean does not explicitly depend on another through properties or constructor arguments, but rather depends on the side effects of another bean’s initialization.
May be used on any class directly or indirectly annotated with org.springframework.stereotype.Component or on methods annotated with Bean.
Using DependsOn at the class level has no effect unless component-scanning is being used. If a DependsOn-annotated class is declared via XML, DependsOn annotation metadata is ignored, and is respected instead.
從java doc中可以看出,@DependsOn
注解可以用來控制bean的創建順序,該注解用於聲明當前bean依賴於另外一個bean。所依賴的bean會被容器確保在當前bean實例化之前被實例化。
一般用在一個bean沒有通過屬性或者構造函數參數顯式依賴另外一個bean,但實際上會使用到那個bean或者那個bean產生的某些結果的情況。
用法
- 直接或者間接標注在帶有
@Component
注解的類上面; - 直接或者間接標注在帶有
@Bean
注解的方法上面; - 使用
@DependsOn
注解到類層面僅僅在使用 component-scanning 方式時才有效;如果帶有@DependsOn
注解的類通過XML方式使用,該注解會被忽略,<bean depends-on="..."/>
這種方式會生效。
例如,我們有一個FileProcessor
依賴於FileReader
和FileWriter
,FileReader
和FileWriter
需要在FileProcessor
之前初始化:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
public class Config {
public FileProcessor fileProcessor(){
return new FileProcessor();
}
public FileReader fileReader() {
return new FileReader();
}
public FileWriter fileWriter() {
return new FileWriter();
}
}
|
也可以在Component
上標注:
1
2
3
|
public class FileProcessor {}
|
屬性注入和構造器注入
上面說到@DependsOn
注解時提到,它一般用在一個bean沒有通過屬性或者構造函數參數顯式依賴另外一個bean,但實際上會使用到那個bean或者那個bean產生的某些結果的情況。
如果bean直接依賴於另一個bean,我們可以將其通過屬性或者構造函數引入進來。
而使用構造函數的方法顯示依賴一個bean,能夠保證被依賴的bean先初始化。但是屬性注入不可以。
constructor-injection automatically enforces the order and completeness of the instantiated.
因此,我們可以在Component中使用構造函數顯示注入依賴的bean:
1
2
3
4
|
public MyComponent(@Qualifier("jedisTemplateNew") JedisTemplate jedisTemplateNew) {
}
|
注意,需要使用@Qualifier
限定bean名稱時,不能標注在構造方法上,而是應該標注在參數上。原因跟@Resource
不能標注構造方法一樣,它不知道你要限定哪個參數。
假設有兩個service,OrderService1
依賴於OrderService2
:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
public class OrderService1 {
private static final Logger LOGGER = LoggerFactory.getLogger(OrderService1.class);
private OrderService2 orderService2;
public OrderService1(OrderService2 orderService2) {
LOGGER.info(
"OrderService1 constructor");
this.orderService2 = orderService2;
}
public String name() {
String name = orderService2.name();
LOGGER.info(
"OrderService1 print orderService2 name={}", name);
return "orderService1";
}
}
public class OrderService2 {
private static final Logger LOGGER = LoggerFactory.getLogger(OrderService2.class);
public OrderService2() {
LOGGER.info(
"OrderService2 constructor");
}
public String name() {
return "orderService2";
}
}
|
對應的Configuration:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
public class OrderService1Config {
private static final Logger LOGGER = LoggerFactory.getLogger(OrderService1Config.class);
private OrderService2Config orderService2Config;
public OrderService1 orderService1() {
LOGGER.info(
"orderService1 init");
return new OrderService1(orderService2Config.orderService2());
}
}
public class OrderService2Config {
private static final Logger LOGGER = LoggerFactory.getLogger(OrderService2Config.class);
public OrderService2 orderService2() {
LOGGER.info(
"orderService2 init");
return new OrderService2();
}
}
|
輸出:
1
2
3
4
|
c.m.s.config.OrderService1Config : orderService1 init
c.m.s.config.OrderService2Config : orderService2 init
c.m.s.service.OrderService2 : OrderService2 constructor
c.m.s.service.OrderService1 : OrderService1 constructor
|
可以看出,OrderService2
先初始化。
換一種OrderService1
寫法,使用屬性注入:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
public class OrderService1 {
private static final Logger LOGGER = LoggerFactory.getLogger(OrderService1.class);
private OrderService2 orderService2;
public void setOrderService2(OrderService2 orderService2) {
this.orderService2 = orderService2;
}
public OrderService1() {
LOGGER.info(
"OrderService1 constructor");
}
public String name() {
String name = orderService2.name();
LOGGER.info(
"OrderService1 print orderService2 name={}", name);
return "orderService1";
}
}
public class OrderService1Config {
private static final Logger LOGGER = LoggerFactory.getLogger(OrderService1Config.class);
private OrderService2Config orderService2Config;
public OrderService1 orderService1() {
LOGGER.info(
"orderService1 init");
OrderService1 orderService1 =
new OrderService1();
orderService1.setOrderService2(orderService2Config.orderService2());
return orderService1;
}
}
|
輸出:
1
2
3
4
|
c.m.s.config.OrderService1Config : orderService1 init
c.m.s.service.OrderService1 : OrderService1 constructor
c.m.s.config.OrderService2Config : orderService2 init
c.m.s.service.OrderService2 : OrderService2 constructor
|
可以看出,OrderService2
並沒有先初始化。
當然,OrderService1Config
也可以使用構造器注入:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
public class OrderService1Config {
private static final Logger LOGGER = LoggerFactory.getLogger(OrderService1Config.class);
private final OrderService2Config orderService2Config;
public OrderService1Config(OrderService2Config orderService2Config) {
this.orderService2Config = orderService2Config;
}
public OrderService1 orderService1() {
LOGGER.info(
"orderService1 init");
OrderService1 orderService1 =
new OrderService1();
orderService1.setOrderService2(orderService2Config.orderService2());
return orderService1;
}
}
|
參考:
@Order in Spring
Controlling Bean Creation Order with @DependsOn Annotation