首页 > 编程语言 > 详细

Java测试类获取spring bean方法

时间:2015-03-30 17:53:01      阅读:192      评论:0      收藏:0      [点我收藏+]

Java测试类获取spring bean方法  

http://blog.163.com/lizhenming_2008/blog/static/76558333201362094243911/

 
 
1、通过spring上下文
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationcontext.xml");
DataSource ds = (DataSource) ctx.getBean("dataSource");
2、Resource类
Resource rs = new FileSystemResource("**/**/appliactioncontext.xml");
BeanFactory factory = new XmlBeanFactory(rs);
DataSource ds = (DataSource) factory.getBean("dataSource");
3、用接口类WebApplicationContext来取
private WebApplicationContext wac;
        wac = WebApplicationContextUtils.getRequiredWebApplicationContext(his.getServletContext());
        wac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
      JdbcTemplate jdbcTemplate = (JdbcTemplate) ctx.getBean("jdbcTemplate");
其中,jdbcTemplate为spring配置文件中的一个bean的id值。
 
读取属性(properties)文件
1、利用spring读取properties 文件
BeanDefinitionRegistry reg = new DefaultListableBeanFactory();
   PropertiesBeanDefinitionReader reader = new PropertiesBeanDefinitionReader(reg);
   reader.loadBeanDefinitions(new ClassPathResource("beanConfig.properties"));
   BeanFactory factory = (BeanFactory) reg;
   HelloBean helloBean = (HelloBean)factory.getBean("helloBean");
2、利用java.util.Properties读取属性文件
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("ipConfig.properties");
   Properties p = new Properties();
   try {
   p.load(inputStream);
   } catch (IOException e1)  {
   e1.printStackTrace();
   }

Java测试类获取spring bean方法

原文:http://www.cnblogs.com/lemontee/p/4378403.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!