【spring教程之一】建立一個最簡單的spring例子,spring教程例子
1、首先spring的主要思想,就是依賴注入。簡單來說,就是不需要手動new對象,而這些對象由spring容器統一進行管理。
2、例子結構
如所示,採用的是maven工程。
2、pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>SpringExample001</groupId> <artifactId>SpringExample001</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.2.5.RELEASE</version> </dependency> </dependencies></project>
3、spring.xml
<?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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <bean id="do" class="com.test.pro.Do"/></beans>
4、Do.java
package com.test.pro;public class Do {public void speaking(){System.out.println("speaking.......");}}
5、測試類別
package com.test.pro;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class Main {public static void main(String[] args) {// TODO Auto-generated method stubApplicationContext ctx=new ClassPathXmlApplicationContext("spring.xml");Do did=(Do)ctx.getBean("do");did.speaking();}}
6、輸出
7、分析
我們可以看到,在核心的spring設定檔中的spring.xml中只有一句話:<bean id="do" class="com.test.pro.Do"/>,這句話指明的是有一個bean檔案,名稱為do,其類的地址是com.test.pro.Do。
然後就是我們的測試類別裡面的一段話:
ApplicationContext ctx=new ClassPathXmlApplicationContext("spring.xml");
Do did=(Do)ctx.getBean("do");
did.speaking();
這裡表示聲明一個上下文類,這個上下文類裝載了設定檔,注意,如果這裡不是採用maven工程的話,一定要注意spring.xml的相對位址,如果實在不確定相對位址是什麼,可以採用絕對位址的方式,例如:
ApplicationContext ctx=new ClassPathXmlApplicationContext("file:H:/spring.xml");
然後就是利用內容物件來獲得在設定檔中聲明過的bean的樣本,並且可以直接調用。
那麼這個bean檔案是什麼時候執行個體化的,如果bean的scope是prototype的,則該Bean的執行個體化是在第一次使用該Bean的時候進行執行個體化 ,可以參考這篇文章:http://www.iteye.com/problems/93479