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