繁体   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