請參閱下面的代碼以獲取更多信息。這會在name()
方法中拋出NullPointerException
(標記爲下面的註釋)。我的理解是,Spring按順序讀取@Configuration
,所以首先自動接線namePrinter
,然後nameProvider
。由於在name()
中使用,因此需要爲NamePrinter
構造函數自動佈線,因此可以解釋NPE。我也知道兩種解決方案:自動裝配訂單NullPointerException
- 一種是按照預期的順序進行訂購。我認爲這應該是Spring的工作。
另一種是通過參數自動裝配,即:
@Bean public Name name(NameProvider nameProvider) { return nameProvider.getName(); }
我也覺得這應該是春天的工作,並希望避免這種情況在有很多參數的情況下 - 使用配置
@Autowired
看起來更在這些情況下我可讀。
一些問題:
- 對於上述的解決2 - 爲什麼春天治療方法參數和自動裝配Autowired類變量不同?
- 是否有合法的原因Spring不會按照依賴順序自動裝入bean,而是選擇源文件定義順序?
- 你遇到過這樣的問題嗎?如果是這樣,你在特定情況下如何解決它們?希望我忽略這裏的東西,可以是有益的
版本:
- 的Java 1.7
- 春4.0.5.RELEASE
代碼:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
interface Name {
String getName();
}
@Component
class NameProvider {
public Name getName() {
return new Name() {
@Override
public String getName() {
return "Foo";
}
};
}
}
@Component
class NamePrinter {
private final Name name;
@Autowired
public NamePrinter(Name name) {
this.name = name;
}
public void print() {
System.out.println(name.getName());
}
}
@Configuration
@ComponentScan(basePackageClasses = { SpringAutowiringPrbConfig.class })
class SpringAutowiringPrbConfig {
@Autowired
private NamePrinter namePrinter;
@Autowired
private NameProvider nameProvider;
@Bean
public Name name() {
return nameProvider.getName(); // NullPointerException here
}
}
public class SpringAutowiringPrb {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
SpringAutowiringPrbConfig.class);
NamePrinter namePrinter = context.getBean(NamePrinter.class);
namePrinter.print();
context.close();
}
}
+1優秀的問題。 –