简体   繁体   中英

Spring Null Pointer Exception in @Autowired Object

Hello I am kind of new in Spring in Dependency Injection.
I have made few config files which has beans inside it and I am injecting those beans using @Autowired annotation.

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();
    }
}

And Last Config

@Configuration
public class ThirdConfig {

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

Here is the service using 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");

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. However you can use the autowired properties in the method with annotation @PostConstruct which will run right after the constructor run.

@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. 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. This is particularly useful when you want to use a class as a bean

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

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

@Autowired
SecondConfig secondConfig;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM