先交代一下具体情况:
1、项目用的SSH
2、使用main方法进行测试的action有注入execSQL、Table5DAO、Table6DAO、Table7DAO、Table8DAO五个bean,第一个bean又注入了其他的bean,后面四个是单独的。
然后上代码:
public static void main(String[] args) throws Exception { try { //实例化spring //ExecSQL与其他bean有关联,因此需要将有关联的xml都包含进来 //这一步有点类似于“web.xml处理各个xml来实例化spring” ApplicationContext ctx=new ClassPathXmlApplicationContext(new String[]{"daosql.xml","pageContorl.xml","base.xml","test_spring.xml"}); System.out.println("*****"+ctx); ExcelEngine excel = new ExcelEngine(); //从spring中获取bean并赋值给excel中对应的参数 excel.execSQL=(ExecSQL)ctx.getBean("ExecSQL"); excel.t5dao=(Table5DAO) ctx.getBean("Table5DAO"); excel.t6dao=(Table6DAO) ctx.getBean("Table6DAO"); excel.t7dao=(Table7DAO) ctx.getBean("Table7DAO"); excel.t8dao=(Table8DAO) ctx.getBean("Table8DAO"); String path = excel.ExportDataToExcel(1484);//测试excel中方法 System.out.println(path); } catch (Exception e) { e.printStackTrace(); } }
最后来个注意点:
有关联的bean所在xml文件必须加载到spring中,否则会报错。
譬如我最开始的只是导入了test_spring.xml没有导其他的(因为我需要的5个bean在该xml文件中都有注入,而其他文件中没有),结果就报错了:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'Table1DAO' defined in class path resource [test_spring.xml]: Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'sessionFactory' is defined。
这是因为我依赖的sessionFactory在base.xml文件中,而这个文件没有加载进来。将互相依赖的bean都加载进行之后就不会报错了。