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方法
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方法
相关文章推荐
- SpringBoot中Junit测试注入Bean失败的解决方法
- Spring 依赖注入,在Main方法中取得Spring控制的实例
- Spring.NET依赖注入框架学习--实例化容器常用方法
- Junit和spring整合,使用Spring托管对象进行依赖注入,方便测试
- spring依赖注入的基本方法及其原理
- 深入 Unity 1.x 依赖注入容器之三:获取对象
- spring入门(6)---set方法注入依赖之null的注入
- Maven打包,并获取依赖的jar包 ,设置main方法启动
- JUnit与Spring的整合——JUnit的TestCase如何自动注入Spring容器托管的对象
- Struts 2在Action中获取Spring容器中所有Bean实例名称的方法
- spring入门(6)---set方法注入依赖之null的注入
- Spring依赖翻转以及注入方法简单介绍
- Spring通过容器获取配置对象及事件注入(学习笔记二)
- 基于JUnit测试Spring MVC的正确方法。(仅限Spring 3.2)
- Spring-Context之六:基于Setter方法进行依赖注入
- 获取spring容器中bean的方法
- Spring依赖注入方式_属性setter方法注入_构造器注入_注解注入
- JUNIT测试Hibernate和Spring的Dao层方法出现的问题
- spring Ioc 依赖注入的三种方式:构造函数注入、setter方法注入和接口注入
- Spring控制反转和依赖注入两个概念以及容器