您的位置:首页 > 编程语言 > Java开发

Spring依赖注入,在main方法或junit测试类里获取得Spring容器

2016-12-08 16:39 996 查看
学spring入门的时候就得先学会使用如何在普通的javabean里获取application.xml中配置的bean

java:

  ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"});

  BeanFactory factory = (BeanFactory) context;

  UserServiceImpl userservice = (UserServiceImpl ) factory.getBean("userservice");

   或者:

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");

    context.start();

    DemoService demoService = (DemoService) context.getBean("demoService"); // 获取bean

    String hello = demoService.sayHello("world"); // 执行bean方法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: