import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.Properties; import org.junit.Test; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; /** * BeanFactory只有依賴注入功能沒有AOP功能, ApplicationContext繼承自BeanFactory有AOP功能 */ public class GetBeanFactory { /** * 加載項目內的配置文件,讀取classPath之下的文件 */ public void test01() { Resource resource = new ClassPathResource("applicationContext.xml"); BeanFactory bf = new XmlBeanFactory(resource); StudentAction studentService = (StudentAction) bf .getBean("StudentAction"); System.out.println(studentService); } /** * 加載項目外的配置文件,File讀取C盤下的文件 */ public void test02() { Resource resource = new FileSystemResource("C:/applicationContext.xml"); BeanFactory beanFactory = new XmlBeanFactory(resource); StudentAction studentAction = (StudentAction) beanFactory .getBean("studentAction"); System.out.println(studentAction); } /** * 讀取Tomcat中的application配置文件, 必須導入Spring3-Web.jar包 */ public void test03() { /* * 將下面的代碼必須放到jsp頁面裏面執行 <% org.springframework.core.io.Resource * resource=null; org.springframework.beans.factory.BeanFactory * beanFactory=null; resource=new * org.springframework.web.context.support * .ServletContextResource(application * ,"/WEB-INF/classes/applicationContext.xml"); beanFactory=new * org.springframework.beans.factory.xml.XmlBeanFactory(resource); * System.out.println(beanFactory); %> */ } /** * ApplicationContext繼承自BeanFactory有AOP功能 */ public void test04() { ApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml"); StudentService studentService = (StudentService) context .getBean("studentService"); studentService.save(new Student("test", 22)); } /** * ApplicationContext繼承自BeanFactory有AOP功能 */ public void test05() { ApplicationContext context = new FileSystemXmlApplicationContext( "C:/applicationContext.xml"); System.out.println(context.getBeanDefinitionCount());// 定義bean的總數 } /** * ApplicationContext繼承自BeanFactory有AOP功能 */ public void test06() { String[] filepath = { "applicationContext.xml" }; ApplicationContext factory = new ClassPathXmlApplicationContext( filepath); StudentService studentService = (StudentService) factory .getBean("studentService"); } /** * 用Spring讀取properties文件 */ @Test public void test07() throws Exception, Exception { Resource r = new ClassPathResource("ssh.properties"); Properties p=new Properties(); p.load(new FileInputStream(r.getFile())); System.out.println(p.get("studentDao")); } @Test public void test08() throws Exception, Exception { Resource r = new ClassPathResource("a.txt"); } }