Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

annotation - How load Spring configuration class?

Tags:

java

spring

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!

like image 662
boden Avatar asked Apr 10 '26 14:04

boden


1 Answers

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.

like image 83
morher Avatar answered Apr 12 '26 04:04

morher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!