文檔版本 | 開發工具 | 測試平臺 | 工程名字 | 日期 | 作者 | 備註 |
---|---|---|---|---|---|---|
V1.0 | 2016.06.21 | lutianfei | none |
- 本文內容
- Spring框架的概述
- Spring的快速入門
- Spring 工廠接口
- 在MyEclipse 配置Spring的xml文件提示
- IoC容器裝配Bean(xml配置方式)
- Ioc容器裝配Bean(註解方式)
- 在web項目中集成Spring
- Spring 整合 junit4 測試
Spring框架學習路線
- Spring的Ioc
- Spring的AOP , AspectJ
- Spring的事務管理
Spring框架的概述
什麼是Spring
Spring是分層的JavaSE/EE full-stack(一站式) 輕量級開源框架
SUN提供的EE的三層結構:web層、業務層、數據訪問層(持久層,集成層)
- Struts2是web層基於MVC設計模式框架.
- Hibernate是持久的一個ORM的框架.
Spring框架有對三層的一站式解決方案:
- web層:Spring MVC
- 持久層:JDBC Template
- 業務層:Spring的Bean管理
Spring的出現是爲了取代EJB的臃腫、低效、脫離現實
Spring的核心
IOC:(Inverse of Control 反轉控制)
- 控制反轉:將對象的創建權,交由Spring完成.
AOP : Aspect Oriented Programming 是 面向對象的功能延伸.不是替換面向對象,是用來解決OO中一些問題.
Spring的版本
- Spring3.x和Spring4.x Spring4需要整合hibernate4.
Spring優點
- 方便解耦,簡化開發
- Spring就是一個大工廠,可以將所有對象創建和依賴關係維護,交給Spring管理
- Spring就是一個大工廠,可以將所有對象創建和依賴關係維護,交給Spring管理
- AOP編程的支持
- Spring提供面向切面編程,可以方便的實現對程序進行權限攔截、運行監控等功能
- 聲明式事務的支持
- 只需要通過配置就可以完成對事務的管理,而無需手動編程
- 方便程序的測試
- Spring對Junit4支持,可以通過註解方便的測試Spring程序
- 方便集成各種優秀框架
- Spring不排斥各種優秀的開源框架,其內部提供了對各種優秀框架(如:Struts、Hibernate、MyBatis、Quartz等)的直接支持
- 降低JavaEE API的使用難度
- Spring 對JavaEE開發中非常難用的一些API(JDBC、JavaMail、遠程調用等),都提供了封裝,使這些API應用難度大大降低
Spring體系結構
- Spring 框架是一個分層架構,它包含一系列的功能要素並被分爲大約20個模塊。這些模塊分爲Core Container、Data Access/Integration、Web、AOP(Aspect Oriented Programming)、Instrumentation和測試部分,如下圖所示:
Spring的快速入門
1. 下載Spring的開發包
官方下載Spring 3.x 最新開發版本
Spring開發包 :
spring-framework-3.2.0.RELEASE-dist.zip
- docs : spring框架api和規範
- libs : spring開發的jar包
- schema : XML的約束文檔.
- Spring開發中的依賴包 :
spring-framework-3.0.2.RELEASE-dependencies.zip
2. 創建web工程引入相應jar包
- spring-beans-3.2.0.RELEASE.jar
- spring-context-3.2.0.RELEASE.jar
- spring-core-3.2.0.RELEASE.jar
spring-expression-3.2.0.RELEASE.jar
開發的日誌記錄的包:
- com.springsource.org.apache.commons.logging-1.1.1.jar : 用於整合其他的日誌的包(類似Hibernate中slf4j)
- com.springsource.org.apache.log4j-1.2.15.jar
3. 創建Spring的配置文件
- 在src下創建一個applicationContext.xml
- 引入XML的約束
- 找到xsd-config.html.引入beans約束
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- bean definitions here -->
</beans>
4. 在配置中配置類
<!-- 通過一個<bean>標籤設置類的信息,通過id屬性爲類起個標識. -->
<bean id="userService" class="cn.itcast.spring3.demo1.HelloServiceImpl"></bean>
5. 創建測試類
- ApplicationContext 應用上下文,加載Spring 框架配置文件
- 加載classpath:
- new ClassPathXmlApplicationContext(“applicationContext.xml”);
- 加載磁盤路徑:
- new FileSystemXmlApplicationContext(“applicationContext.xml”);
@Test
// Spring開發
public void demo2() {
// 創建一個工廠類.
ApplicationContext applicationContext = new ClassPathXmlApplicationContext( "applicationContext.xml");
HelloService helloService = (HelloService) applicationContext.getBean("userService");
helloService.sayHello();
}
類創建的傳統方式
HelloTest類中使用 HelloService類對象
- 傳統方式: HelloService helloService = new HelloService();
- 傳統方式: HelloService helloService = new HelloService();
IoC Inverse of Control 反轉控制的概念,就是將原本在程序中手動創建HelloService對象的控制權,交由Spring框架管理,簡單說,就是創建HelloService對象控制權被反轉到了Spring框架
IOC和DI區別
- IOC:控制反轉:將對象的創建權,由Spring管理.
DI:依賴注入:在Spring創建對象的過程中,把對象依賴的屬性注入到類中.
面向對象中對象之間的關係;
- 依賴:
public class A{
private B b;
}
* 繼承:is a
* 聚合:
* 聚集:
* 組合:
BeanFactory與ApplicationContext區別
- ApplicationContext類繼承了BeanFactory
- BeanFactory在使用到這個類的getBean()方法的時候,纔會加載這個類.
- ApplicationContext類加載配置文件的時候,創建所有的類
ApplicationContext對BeanFactory提供了擴展:
- 國際化處理
- 事件傳遞
- Bean自動裝配
- 各種不同應用層的Context實現
- 早期開發使用BeanFactory.
Eg:
@Test
public void demo4(){
// ClassPathResource FileSystemResource
BeanFactory beanFactory = new XmlBeanFactory(new FileSystemResource("applicationContext.xml"))</u>;
HelloService helloService = (HelloService) beanFactory.getBean("userService");
helloService.sayHello();
}
MyEclipse配置XML提示
- Myeclipse window-preferences- 搜索xml catalog
- 選中User Specified Entries – Add 操作
- location 瀏覽選中 解壓spring 包中 schema\beans\spring-beans-3.2.xsd
- 修改Key type 爲 Schema location
- key 修改爲 http://www.springframework.org/schema/beans/spring-beans.xsd
Spring框架Bean實例化的方式
- 三種方式實例化Bean
- 構造方法實例化(默認無參數)
- 靜態工廠實例化
- 實例工廠實例化
無參數構造方法的實例化
<!-- 默認情況下使用的就是無參數的構造方法. -->
<bean id="bean1" class="cn.itcast.spring3.demo2.Bean1"></bean>
靜態工廠實例化 – 簡單工廠模式
<!-- 第二種使用靜態工廠實例化 -->
<bean id="bean2" class="cn.itcast.spring3.demo2.Bean2Factory" factory-method="getBean2"></bean>
實例工廠實例化 – 工廠方法模式
<!-- 第三種使用實例工廠實例化 -->
<bean id="bean3" factory-bean="bean3Factory" factory-method="getBean3"></bean>
<bean id="bean3Factory" class="cn.itcast.spring3.demo2.Bean3Factory"/>
public class PersonServiceFactory {
public PersonService createPersonService(){
return new PersonServiceImpl();
}
}
- eg:
/**
* Bean的實例化的測試
*
* @author 姜濤
*
*/
public class SpringTest2 {
@Test
// 無參數的構造方法的實例化
public void demo1() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");
Bean1 bean1 = (Bean1) applicationContext.getBean("bean1");
System.out.println(bean1);
}
@Test
// 靜態工廠實例化
public void demo2() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");
Bean2 bean2 = (Bean2) applicationContext.getBean("bean2");
System.out.println(bean2);
}
@Test
// 實例工廠實例化
public void demo3() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");
Bean3 bean3 = (Bean3) applicationContext.getBean("bean3");
System.out.println(bean3);
}
Bean的其他配置
Bean的命名 id屬性和name屬性
- 一般情況下,裝配一個Bean時,通過指定一個id屬性作爲Bean的名稱
- id 屬性在IoC容器中必須是唯一的
- id 的命名要滿足XML對ID屬性命名規範
- id遵守XML約束的id的約束.id約束保證這個屬性的值是唯一的,而且必須以字母開始,可以使用字母、數字、連字符、下劃線、句話、冒號
- 如果Bean的名稱中含有特殊字符,就需要使用name屬性
- 例如:
<bean name="#person" class="cn.itcast.bean.Person"/>
- 因爲name屬性可以相同,所以後出現Bean會覆蓋之前出現的同名的Bean
類的作用範圍
scope屬性 :
singleton
: 單例的(默認的值)prototype
: 多例的request
: web開發中創建了一個對象,將這個對象存入request範圍,request.setAttribute();session
: web開發中.創建了一個對象,將這個對象存入session範圍,session.setAttribute();globalSession
:一般用於Porlet應用環境.指的是分佈式開發.不是porlet環境,globalSession等同於session;
實際開發中主要使用
singleton
,prototype
Bean的生命週期
- 配置Bean的初始化和銷燬的方法:在xml文件中加入:
- init-method=”setup”
- destroy-method=”teardown”
- 執行銷燬的時候,必須手動關閉工廠,而且只對scope=singleton有效
- 必須用子類執行 ClassPathXmlApplicationContext 中的close方法來實現。
Bean的生命週期的11個步驟
- 1 . bean對象實例化 : instantiate bean
- 2 . 屬性的注入: populate properties : 封裝屬性
- 3 . 注入配置的類的名稱 : 如果Bean實現
BeanNameAware
執行 setBeanName - 4 . 注入applicationContext : 如果Bean實現
BeanFactoryAware
或者 k 設置工廠 setBeanFactory 或者上下文對象 setApplicationContext - 5 . 初始化之前執行操作 : 如果存在類實現
BeanPostProcessor
(後處理Bean),執行postProcessBeforeInitialization
- 需要添加此標籤:
<bean class="cn.itcast.spring3.demo4.MyBeanPostProcessor"></bean>
- 6 . 屬性設置後執行操作 : 如果Bean實現
InitializingBean
執行 afterPropertiesSet
- 需要添加此標籤:
- 7 . 調用手動設置的初始化方法 : 調用
<bean init-method="init">
指定初始化方法 init - 8 . 初始化後執行操作 : 如果存在類實現
BeanPostProcessor
(處理Bean),執行 postProcessAfterInitialization - 9 . 執行業務處理
- 10 . 調用銷燬的方法 : 如果Bean實現
DisposableBean
執行 destroy 11 . 調用手動銷燬方法 : 調用
<bean destroy-method="customerDestroy">
指定銷燬方法 customerDestroy案例:在CustomerService類的add方法之前進行權限校驗
xml配置
<bean id="customerService" class="cn.itcast.spring3.demo4.CustomerServiceImpl" init-method="setup" destroy-method="teardown">
<property name="name" value="itcast"></property>
</bean>
<bean class="cn.itcast.spring3.demo4.MyBeanPostProcessor"></bean>
//這裏不需要寫id,因爲這是由Spring容器自動調用的。
- CustomerService & CustomerServiceImpl
public interface CustomerService {
public void add();
public void find();
}
public class CustomerServiceImpl implements CustomerService, BeanNameAware,ApplicationContextAware,InitializingBean,DisposableBean {
private String name;
public void setName(String name) {
System.out.println("第二步:屬性的注入.");
this.name = name;
}
public CustomerServiceImpl() {
super();
System.out.println("第一步:實例化類.");
}
public void add(){
System.out.println("添加客戶...");
}
public void find(){
System.out.println("查詢客戶...");
}
public void setBeanName(String name) {
System.out.println("第三步:注入配置的類的名稱"+name);
}
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
System.out.println("第四步:注入applicationContext"+applicationContext);
}
public void afterPropertiesSet() throws Exception {
System.out.println("第六步:屬性設置後執行...");
}
public void setup(){
System.out.println("第七步:調用手動設置的初始化方法...");
}
public void destroy() throws Exception {
System.out.println("第十步:調用銷燬的方法...");
}
public void teardown(){
System.out.println("第十一步:調用手動銷燬方法...");
}
}
- MyBeanPostProcessor
public class MyBeanPostProcessor implements BeanPostProcessor{
/**
* bean:實例對象
* beanName:在配置文件中配置的類的標識.
*/
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("第五步:初始化之前執行...");
return bean;
}
public Object postProcessAfterInitialization(final Object bean, String beanName)
throws BeansException {
System.out.println("第八步:初始化後執行...");
// 動態代理:
if(beanName.equals("customerService")){
Object proxy = Proxy.newProxyInstance(bean.getClass().getClassLoader(), bean.getClass().getInterfaces() , new InvocationHandler() {
// 調用目標方法的時候,調用invoke方法.
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if("add".equals(method.getName())){
System.out.println("權限校驗...");
Object result = method.invoke(bean, args);
//System.out.println(System.currentTimeMillis());
return result;
}
return method.invoke(bean, args);
}
});
return proxy;
}
return bean;
}
}
- Spirng Test
public class SpringTest4 {
@Test
// Bean完整的生命週期
public void demo1() {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");
CustomerService customerService = (CustomerService) applicationContext.getBean("customerService");
customerService.add();
customerService.find();
applicationContext.close();
}
}
//結果如下:
第一步:實例化類
第二步:屬性的注入
第三步:注入配置的類的名稱 customerService
第四步:注入applicationContext org.springframework.context.support.ClassPathXmlApplicationContext@61baa894: startup date [Wed Jun 22 11:49:14 CST 2016]; root of context hierarchy
第五步:初始化之前執行...
第六步:屬性設置後執行...
第七步:調用手動設置的初始化方法...
第八步:初始化後執行...
權限校驗...
添加客戶...
查詢客戶...
11:49:14,863 INFO ClassPathXmlApplicationContext:1042 - Closing org.springframework.context.support.ClassPathXmlApplicationContext@61baa894: startup date [Wed Jun 22 11:49:14 CST 2016]; root of context hierarchy
11:49:14,864 INFO DefaultListableBeanFactory:444 - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@64bfbc86: defining beans [customerService,test.spring3.demo4.MyBeanPostProcessor#0]; root of factory hierarchy
第十步:調用銷燬的方法...
第十一步:調用手動銷燬的方法...
IOC容器裝配Bean
Bean中屬性注入–基於XML方式
IoC容器裝配Bean 基於XML配置方式
- Spring支持
- 構造方法注入
- setter方法注入
構造器注入
- 使用構造方法注入,在Spring配置文件中,通過
<constructor-arg>
設置注入的屬性 (可以通過index或者type注入)
setter方法注入
- 使用setter方法注入,在Spring配置文件中,通過
<property>
設置注入的屬性
<bean id="car2" class="cn.itcast.spring3.demo5.Car2">
<!-- <property>標籤中name就是屬性名稱,value是普通屬性的值,ref:引用其他的對象 -->
<property name="name" value="保時捷"/>
<property name="price" value="5000000"/>
</bean>
setter方法注入對象屬性
<property>
標籤中name就是屬性名稱,value是普通屬性的值,ref:引用其他的對象
名稱空間p:注入屬性
Spring2.5版本引入了
名稱空間p
p:<屬性名>="xxx"
引入常量值p:<屬性名>-ref="xxx"
引用其它Bean對象
引入名稱空間:
xmlns:p="http://www.springframework.org/schema/p"
xml:
<bean id="car2" class="cn.itcast.spring3.demo5.Car2" p:name="寶馬" p:price="400000"/>
<bean id="person" class="cn.itcast.spring3.demo5.Person" p:name="童童" p:car2-ref="car2"/>
SpEL:屬性的注入
- Spring3.0提供注入屬性方式:
- 語法:
<bean id="" value="#{表達式}">
#{'神回覆:哈哈'}
使用字符串#{topicId3}
使用另一個bean#{topicId4.content.toUpperCase()}
使用指定名屬性,並使用方法#{T(java.lang.Math).PI}
使用靜態字段或方法
<bean id="car2" class="cn.itcast.spring3.demo5.Car2">
<property name="name" value="#{'大衆'}"></property>
<property name="price" value="#{'120000'}"></property>
</bean>
<bean id="person" class="cn.itcast.spring3.demo5.Person">
<!--<property name="name" value="#{personInfo.name}"/>-->
<property name="name" value="#{personInfo.showName()}"/>
<property name="car2" value="#{car2}"/>
</bean>
<bean id="personInfo" class="cn.itcast.spring3.demo5.PersonInfo">
<property name="name" value="張三"/>
</bean>
SpEL : 集合屬性的注入 – List(數組)
SpEL : 集合類型屬性注入 – Set
SpEL : 集合類型屬性注入 – Map
SpEL :集合類型屬性注入 – Properties
- 綜合案例
<bean id="collectionBean" class="cn.itcast.spring3.demo6.CollectionBean">
<!-- 注入List集合 -->
<property name="list">
<list>
<value>童童</value>
<value>小鳳</value>
</list>
</property>
<!-- 注入set集合 -->
<property name="set">
<set>
<value>杜宏</value>
<value>如花</value>
</set>
</property>
<!-- 注入map集合 -->
<property name="map">
<map>
<entry key="剛剛" value="111"/>
<entry key="嬌嬌" value="333"/>
</map>
</property>
<property name="properties">
<props>
<prop key="username">root</prop>
<prop key="password">123</prop>
</props>
</property>
</bean>
多配置文件的加載
第一種寫法:
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean1.xml",”bean2.xml”);
第二種方法:
<import resource="applicationContext2.xml"/>
Bean的屬性注入–基於註解方式
IoC容器裝配Bean , 基於註解配置方式
Spring2.5 引入註解去定義Bean
@Component
描述Spring框架中Bean
Xml:頭文件中加入context路徑:
xmlns:context=http://www.springframework.org/schema/context
- 最好直接從
dsd-config.html
中複製過來相應的代碼段
- 最好直接從
<?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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- bean definitions here -->
</beans>
- 配置提示操作
- 將紅框中地址複製到
Key
中
- 將紅框中地址複製到
- 引入component-scan標籤:
<context:component-scan base-package="cn.itcast.spring3"/>
,告訴Spring要去掃描哪些包下的類。
- Spring的框架中提供了與
@Component
註解等效的三個註解:
@Repository
用於對DAO實現類進行標註
@Service
用於對Service實現類進行標註
@Controller
用於對Controller實現類進行標註 - 三個註解是爲了讓標註類本身的用途清晰,Spring在後續版本會對其增強
自動裝配 Bean
- 使用
@Autowired
進行自動注入 @Service
標註業務類@Repository
標註DAO@Autowired
默認按照類型進行注入
- 如果存在兩個相同Bean類型,則按照名稱注入
- @Autowired 注入時可以針對成員變量或者setter方法
- 通過@Autowired的required屬性,設置一定要找到匹配的Bean,默認爲true,爲false時表示對異常不關心。
- 使用
@Qualifier
指定注入Bean的名稱
- 使用
Qualifier
指定Bean名稱後,註解Bean必須指定相同名稱
- 使用
普通屬性
- @Value(value=”itcast”)
- private String info;
對象屬性
- 按類型注入
- @Autowired:自動裝配默認使用類型注入.
- 按名稱進行注入
- @Autowired 中有一個屬性required,默認爲true,爲false時表示對異常不關心。
- @Qualifier(“userDao”) 按名稱進行注入.
標準註解@Resource
Spring提供對JSR-250中定義
@Resource
標準註解的支持@Resource
和@Autowired
註解功能相似下面兩個例子等價
@Autowired
@Qualifier("userDao")
private UserDao userDao;
@Resource(name="userDao")
private UserDao userDao;
Bean其他的屬性的配置
- 配置Bean初始化方法和銷燬方法:
- init-method 和 destroy-method.
@PostConstruct
: 初始化@PreDestroy
: 銷燬
配置Bean的作用範圍
- 使用註解配置的Bean和
<bean>
配置的一樣,默認作用範圍都是singleton
- @Scope註解用於指定Bean的作用範圍
Spring3.0可以 使用Java類提供Bean定義信息
Spring3.0以JavaConfig爲核心,提供使用Java類定義Bean信息的方法
@Configuration
指定POJO類爲Spring提供Bean定義信息,代表此類就是一個配置類。@Bean
提供一個Bean定義信息
之前已經通過
component-scan標籤
對配置類進行了掃描,故這裏不需要再進行手動配置掃描了。
@Configuration
public class BeanConfig {
@Bean(name="car")
public Car showCar(){
Car car = new Car();
car.setName("長安");
car.setPrice(40000d);
return car;
}
@Bean(name="product")
public Product initProduct(){
Product product = new Product();
product.setName("空調");
product.setPrice(3000d);
return product;
}
}
實際開發中使用XML還是註解
- XML:
- bean管理
- 註解:
- 注入屬性的時候比較方便
- 兩種方式結合;一般使用XML註冊Bean,使用註解進行屬性的注入
Spring整合web開發
正常整合Servlet和Spring沒有問題的,但是每次執行Servlet的時候加載Spring配置以及加載Spring環境
解決辦法:
- 將加載的信息內容放到
ServletContext
中.ServletContext對象是全局的對象。服務器啓動的時候創建的,在創建ServletContext的時候就加載Spring的環境。 ServletContextListener
:用於監聽ServletContext對象的創建和銷燬的.- 以上解決方法可以通過導入Spring web開發jar包來解決 :
spring-web-3.2.0.RELEASE.jar
- 將加載的信息內容放到
web.xml中的配置
- 將Spring容器初始化,交由web容器負責
- 配置核心監聽器 ContextLoaderListener
- 配置全局參數contextConfigLocation
- 用於指定Spring的框架的配置文件位置(因爲:applicationContext.xml文件與默認位置不一致)
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
獲得WebApplicationContext對象
- 因爲Spring容器已經交由web容器初始化和管理,獲得WebApplicationContext對象,需要依賴ServletContext對象 通常在Servlet中完成:
WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
- 另一種方式
WebApplicationContext applicationContext = (WebApplicationContext) getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
eg:
web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<display-name></display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>UserServlet</servlet-name>
<servlet-class>cn.itcast.servlet.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>/userServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
- UserServlet & UserService
public class UserServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/*ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");*/
WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
UserService userService = (UserService) applicationContext
.getBean("userService");
userService.sayHello();
}
public class UserService {
public void sayHello(){
System.out.println("Hello Spring web...");
}
}
Spring集成JUnit測試
- 1.程序中有Junit環境.
- 2.導入Spring test測試jar包
- spring-test-3.2.0.RELEASE.jar
- 3.測試代碼:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class SpringTest {
@Autowired
private UserService userService;
@Test
public void demo1(){
userService.sayHello();
}
}