boden
boden

Reputation: 1681

annotation - How load Spring configuration class?

I have simple project where I want run method CarDaoImpl::save from Main::runApp. I have class with @Configration annotation but my @Autowired field is null and I receive NullPointerException, because config class not load, how me fix this problem?

public class Main {

    @Autowired
    private CarDao carDao;

    //psvm(){}

    public void runApp(){
        carDao.save(new Car());  //carDao is null
    }
}

Configuration class

@Configuration
public class BeanInit {

    @Bean
    public CarDao carDao(){
        return new CarDaoImpl();
    }
}

Thanks!

Upvotes: 3

Views: 9649

Answers (1)

morher
morher

Reputation: 71

You can add a constructor to Main where you create a new AnnotationConfigApplicationContext and then use that context to initiate the object.

public class Main {

    @Autowired
    private CarDao carDao;

    public Main() {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(BeanInit.class);
        ctx.getAutowireCapableBeanFactory().autowireBean(this);
    }

    //psvm(){}

    public void runApp(){
        carDao.save(new Car());  //carDao is null
    }
}

Please note that this will not make Main a Spring managed bean. For example, adding @Transactional or other aspect oriented annotations to methods in Main will have no effect at all.

I might be a better idea to make the caller of Main::runApp initiate the application context and let Main be a spring managed bean by including it in the configuration. You could then use ctx.getBean(Main.class) to retrieve the bean.

Upvotes: 3

Related Questions