Java测试类获取spring bean方法
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();
}