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

来源:互联网 发布:反arp攻击软件 编辑:程序博客网 时间:2024/06/05 03:31

学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方法


0 0
原创粉丝点击