在有些情况下需要使用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);
         }

  

相关文章:

  • 2022-01-01
  • 2021-10-05
  • 2022-12-23
  • 2022-01-01
  • 2021-12-28
  • 2021-06-30
猜你喜欢
  • 2021-07-08
  • 2021-05-24
  • 2018-05-24
  • 2021-10-19
  • 2021-12-03
  • 2021-10-07
相关资源
相似解决方案