简体   繁体   English

@Autowired对象中的Spring空指针异常

[英]Spring Null Pointer Exception in @Autowired Object

Hello I am kind of new in Spring in Dependency Injection. 您好,我是依赖注入中Spring的新手。
I have made few config files which has beans inside it and I am injecting those beans using @Autowired annotation. 我已经制作了一些配置文件,其中包含bean,并且正在使用@Autowired注解注入这些bean。

Configs: 配置:

@Configuration
@Component
public class FirstConfig {

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

    @Autowired
    SecondConfig secondConfig;

}

SecondConfig SecondConfig

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

And Last Config 和最后的配置

@Configuration
public class ThirdConfig {

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

Here is the service using A() 这是使用A()的服务

@Component
public class XYZService
{
    private C c;

    @Autowired
    private A a;

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

Also, if this helps, 另外,如果这有帮助,

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

I am getting NPE on this line: this.c = a.doSomething("Hello world"); 我在这条线上得到了NPE:this.c = a.doSomething(“ Hello world”);

Any idea what's wrong? 知道有什么问题吗?

You can't use autowired properties in the class consturctor since Spring just inject the @Autowired properties after the creation of that class. 您不能在类构造器中使用自动装配属性,因为Spring只是在创建该类之后注入@Autowired属性。 However you can use the autowired properties in the method with annotation @PostConstruct which will run right after the constructor run. 但是,您可以在带有注解@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");
    }
}

To use one configuration into another you can Import the configuration using @Import(ConfigurationClass.class) annotation. 要将一个配置用于另一个配置,可以使用@Import(ConfigurationClass.class)批注导入配置。 In your case - 就您而言-

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

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

@Autowired
SecondConfig secondConfig;

}

You could also use @ComponentScan annotation to let your configuration automatically detect components from your Configuration file like shown below. 您还可以使用@ComponentScan批注使配置自动从配置文件中检测组件,如下所示。 This is particularly useful when you want to use a class as a bean 当您要将类用作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