簡體   English   中英

@Autowired對象中的Spring空指針異常

[英]Spring Null Pointer Exception in @Autowired Object

您好,我是依賴注入中Spring的新手。
我已經制作了一些配置文件,其中包含bean,並且正在使用@Autowired注解注入這些bean。

配置:

@Configuration
@Component
public class FirstConfig {

    @Bean
    A getA() {
        return new A(secondConfig.getB());
    }

    @Autowired
    SecondConfig secondConfig;

}

SecondConfig

@Configuration
public class SecondConfig {
    @Bean
    B getB() {
        return new B();
    }
}

和最后的配置

@Configuration
public class ThirdConfig {

    @Bean
    D getD() {
        return new D();
    }
}

這是使用A()的服務

@Component
public class XYZService
{
    private C c;

    @Autowired
    private A a;

    public XYZService()
    {
        this.c = a.doSomething("Hello world");
    }    
}

另外,如果這有幫助,

@Component
public class B implements someInteface
{  
    @Autowired
    private D d;
}

我在這條線上得到了NPE:this.c = a.doSomething(“ Hello world”);

知道有什么問題嗎?

您不能在類構造器中使用自動裝配屬性,因為Spring只是在創建該類之后注入@Autowired屬性。 但是,您可以在帶有注解@PostConstruct的方法中使用自動裝配屬性,該屬性將在構造函數運行后立即運行。

@Component
public class XYZService
{
    private C c;

    @Autowired
    private A a;

    public XYZService()
    {
        // Move the initialization to @PostConstruct
    }    

    @PostConstruct
    private void init() {
        this.c = a.doSomething("Hello world");
    }
}

要將一個配置用於另一個配置,可以使用@Import(ConfigurationClass.class)批注導入配置。 就您而言-

@Configuration
@Component
@Import(SecondConfig.class)
public class FirstConfig {

@Bean
A getA() {
    return new A(secondConfig.getB());
}

@Autowired
SecondConfig secondConfig;

}

您還可以使用@ComponentScan批注使配置自動從配置文件中檢測組件,如下所示。 當您要將類用作Bean時,這特別有用

@Configuration
@Component
@ComponentScan(basepackages = "com.yourBasePackage")
public class FirstConfig {

@Bean
A getA() {
    return new A(secondConfig.getB());
}

@Autowired
SecondConfig secondConfig;

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM