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

问题描述 投票:0回答:2

您好,我在依赖注入Spring中是一种新的东西。 我做了一些配置文件,里面有bean,我使用@Autowired注释注入这些bean。

CONFIGS:

@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”);

知道什么是错的吗?

java spring dependency-injection
2个回答
2
投票

您不能在类consturctor中使用自动装配属性,因为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");
    }
}

0
投票

要将一个配置用于另一个配置,可以使用@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;

}
© www.soinside.com 2019 - 2024. All rights reserved.