最近在看JAVAEE的spring框架,剛成功配置了一個小案例,因而記錄下來java
先看看 項目的目錄結構吧 spring
配置文件不能不看啊框架
<!-- lang: java --> <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd "> <bean id="student" class="wang.spring.Student" scope="prototype"> <property name="ID"> <value>001</value> </property> </bean> <bean id="male" class="wang.spring.Male"></bean> <bean id="female" class="wang.spring.Female"></bean> </beans>
接下來是一個接口 Person.java測試
<!-- lang: java --> package wang.spring; public interface Person { public void run(); }
實現類 Male.javaprototype
<!-- lang: java --> package wang.spring; public class Male implements Person { public Male(){ System.out.println("Male create..."); } public void run(){ System.out.println("I'm a male..."); } }
實現類 Female.javacode
<!-- lang: java --> package wang.spring; public class Female implements Person{ public Female(){ System.out.println("Female create..."); } public void run(){ System.out.println("I'm a female..."); } }
最後就是測試類了 Test.javaxml
<!-- lang: java --> package wang.spring; 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 Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub // BeanFactory factory=new XmlBeanFactory(new ClassPathResource("spring.xml")); // Student st=(Student)factory.getBean("student"); // ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml"); // Student st=(Student)context.getBean("student"); // st.say(); // // Student student=(Student)context.getBean("student"); // student.say(); ApplicationContext per=new ClassPathXmlApplicationContext("spring.xml"); Person person=(Person)per.getBean("male"); person.run(); Person p=(Person)per.getBean("female"); p.run(); } }
至此,一個小的spring案例就能夠運行在你的java環境裏了對象
能夠看出spring對 對象的管理,它在容器裏面new 了一系列對象, 在應用程序裏面就能夠去調用,而不須要去new了 同時注意,你的那些在spring.xml裏面配置的類必須能實例化,不能是靜態的接口