Java类中加载Spring中的ApplicationContext.xml文件的方式

时间:2020-11-24 17:28:44
Xml代码  Java类中加载Spring中的ApplicationContext.xml文件的方式
  1. <1>、利用ClassPathXmlApplicationContext,可以从classpath中读取XML文件  
  2. //读取一个文件  
  3.  1. ApplicationContext contextnew ClassPathXmlApplicationContext("applicationContext.xml");   
  4. UserDAO userDAO= (UserDAO )context.getBean("userDAO");   
  5. //读取多个文件  
  6.  2.ClassPathXmlApplicationContext resourcenew ClassPathXmlApplicationContext(new String[]  
  7. {"applicationContextconfig.xml","applicationContext.xml","applicationContext-data.xml"});   
  8. BeanFactory factoryresource;  
  9. UserDAO userDAO= (UserDAO ) factory.getBean("userDAO ");  
  10.  
  11. <2>、利用ClassPathResource,可以从classpath中读取XML文件  
  12. Resource resourcenew ClassPathResource("applicationContext.xml");   
  13. BeanFactory bf=new XmlBeanFactory(resource );   
  14. UserDAO userDAO= (UserDAO )bf.getBean("userDAO ");   

  15. <3>、利用XmlWebApplicationContext读取  
  16. XmlWebApplicationContext xmlctx = new XmlWebApplicationContext();   
  17. xmlctx.setConfigLocations(new String[] {"/WEB-INF/ applicationContext.xml");   
  18. xmlctx.setServletContext(pageContext.getServletContext());   
  19. xmlctx.refresh();  
  20.  UserDAO userDAO= (UserDAO ) xmlctx.getBean("userDAO ");   

  21. <4>、利用FileSystemResource读取  
  22.  Resource resourcenew FileSystemResource("E:/Java/spring/WebRoot/WEB-INF/classes/ applicationContext.xml");   
  23. BeanFactory factorynew XmlBeanFactory(resource );  
  24.  UserDAO userDAO= (UserDAO )factory.getBean("userDAO ");   
  25.    注意:利用FileSystemResource,则配置文件必须放在project直接目录下,或者写明绝对路径,否则就会抛出找不到文件的异常  

  26. <5>、利用FileSystemXmlApplicationContext读取,可以指定XML定义文件的相对路径或者绝对路径来读取定义文件。  
  27. 1.String[] path={"WebRoot/WEB-INF/applicationContext.xml","WebRoot/WEB-INF/applicationContext_config.xml"};   
  28. ApplicationContext context = new FileSystemXmlApplicationContext(path);  
  29. 2. String path="WebRoot/WEB-INF/applicationContext*.xml";   
  30. ApplicationContext context = new FileSystemXmlApplicationContext(path);   
  31. 3.ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:地址");