1、创建bean
package Test201307; public class MessageBean { private String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
2、创建spring配置文件
Spring framework application test!
3、测试类
package Test201307; import java.net.URL; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.core.io.ClassPathResource; public class SpringTest { /** * @param args */ public static void main(String[] args) { //String path = System.getProperty("user.dir"); //System.out.println("path:"+path); //System.out.println("path:"+SpringTest.class.getClassLoader().getResource("")); //System.out.println("path:"+SpringTest.class.getResource("")); //System.out.println("path:"+SpringTest.class.getResource("/")); //System.out.println("path:"+ClassLoader.getSystemResource("")); //System.out.println("path:"+Thread.currentThread().getContextClassLoader().getResource("")); URL urlAb = SpringTest.class.getResource(""); URL urlSt = SpringTest.class.getResource("/"); String path = urlAb.toString().replace(urlSt.toString(), ""); System.out.println("path->"+path); // 创建ClassPathResource对象,类加载器将在classpath中查找beans-config.xml文件. ClassPathResource resource = new ClassPathResource(path+"beans-config.xml"); /*spring 根据beans-config.xml文件中的配置信息创建BeanFactory的实例, 同时完成bean的创建和属性值得注入。*/ BeanFactory beanFactory = new XmlBeanFactory(resource); // getBean() 取得bean实例 MessageBean bean = (MessageBean)beanFactory.getBean("messageBean");//从配置文件中 System.out.println(bean.getMessage()); /* sping 容器有两个接口:BeanFactory和ApplicatoinContext,都被称为:spring上下文 ,它们都是bean的工厂。但是,ApplicatoinContext是BeanFactory的子接口,提供了更多 的功能。 */ //方式2 ApplicationContext ac = new ClassPathXmlApplicationContext(path+"beans-config.xml"); MessageBean messageBean_2 = (MessageBean)ac.getBean("messageBean"); System.out.println(messageBean_2.getMessage()); } }