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