main方法中注入Spring bean


在有些情况下需要使用main使用Spring bean,但是main方法启动并没有托管给Spring管理,会导致bean失败,报空指针异常。

可以使用 ClassPathXmlApplicationContext 加载配置文件,获获取bean:

public static void main(String[] args) {
            @SuppressWarnings("resource")
            ClassPathXmlApplicationContext  context = new ClassPathXmlApplicationContext("classpath:spring.xml");//spring.xml文件为spring配置文件
            context.registerShutdownHook();
            context.start();
            CityConfig cityConfig=(CityConfig)context.getBean("cityConfig");//获取CityConfig bean
            System.out.println(cityConfig);
         }

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM