天天看點

Spring架構整體鞏固學習 第一部分提供整理相關資源下載下傳目錄:http://download.csdn.net/detail/u010879420/9921811一、Spring簡介二、spring的bean管理三、Spring的AOP

提供整理相關資源下載下傳目錄:http://download.csdn.net/detail/u010879420/9921811

一、Spring簡介

1.spring是開源的輕量級架構

2.spring核心主要兩部分

(1) aop: 面向切面程式設計,擴充功能不是修改源代碼實作

(2)ioc : 控制反轉,

---------比如一個類,在類裡面有方法(不是靜态方法),調用類裡面的方法,建立類的對象,使用對象調用方法,建立類對象的過程,需要new出來對象

---------把對象的建立不是通過new方式實作,而是交給spring配置建立類對象

3.spring是一站式架構

spring在javaEE三層結構中,每一層都提供不同的解決技術

Web層:springMVC

SERVICE層:spring的ioc

dao層:spring的jdbcTemplate

4.spring版本

Spring4.X

5.Spring準備jar包

spring基礎包:

spring-beans-4.2.5.RELEASE.jar

spring-context-4.2.5.RELEASE.jar

spring-core-4.2.5.RELEASE.jar

spring-expression-4.2.5.RELEASE.jar

日志包:

commons-logging-1.2.jar

log4j-1.2.17.jar

二、spring的bean管理

1.    Bean執行個體化的方式

1)    使用類的無參構造建立對象(重點☆☆☆☆☆☆)

   <!-- 無參構造 -->

   <bean id="User"class="cn.zzh.ioc.User"></bean>

類裡面沒有無參的構造,出現異常

2)    使用靜态工廠建立

建立靜态方法,傳回類對象。

建立實體

package cn.zzh.po;

public class Bean1 {

   public void getname() {

      System.out.println("Bean1__________");

   } 

}

建立工廠類

public class Bean1Factory {

   public static Bean1 getBean1() {

      returnnew Bean1();

   }

}

XML中配置

<!-- 使用靜态工廠建立-->

   <bean id="bean1"class="cn.zzh.BeanFactory.Bean1Factory"factory-method="getBean1"></bean>

3)    使用執行個體工廠建立

建立不是靜态的方法,傳回類對象

建立實體

package cn.zzh.po;

public class Bean2 {

   public void getname() {

      System.out.println("Bean2__________");

   }

}

建立工廠類

package cn.zzh.BeanFactory;

import cn.zzh.po.Bean2;

public class Bean2Factory {

   public Bean2 getBean2() {

      return new Bean2();

   }

}

XML中配置

   <!-- 使用執行個體工廠建立-->

   <beanid="bean2Factory"class="cn.zzh.BeanFactory.Bean2Factory"></bean>

   <beanid="bean2"factory-bean="bean2Factory"factory-method="getBean2"></bean>

測試代碼

   @Test

   public void testFactory2() {

      ApplicationContext context =new ClassPathXmlApplicationContext("ApplicationContext.xml");

      Bean2Factory bean2Factory = (Bean2Factory)context.getBean("bean2Factory");

      Bean2 bean2 = (Bean2) context.getBean("bean2");

      System.out.println(bean2);

      bean2.getname();

}

2.    Bean标簽常用屬性

1)    Id

給Bean取得名稱

2)    Name

與Id屬性的作用一樣

3)    Class

建立類的全路徑

4)    Scope

Bean的作用範圍,其取值有:

Singleton:預設值,單例模式

Prototype:多例

Request:WEB項目中,Spring建立一個Bean的對象,将對象放入request中。

Session:WEB項目中,Spring建立一個Bean的對象,将對象放入session中。

globalSession:WEB項目中,Spring建立一個Bean的對象,将對象放入globleSession中。

3.    屬性注入介紹

1)    使用參數構造注入

實體建立

package cn.zzh.po;

public class PropertyDemo {

   private Stringname;

   public PropertyDemo(Stringname) {

      this.name =name;

   }

   public String getName() {

      return name;

   } 

}

XML配置

   <!-- 使用有參數構造屬性-->

   <beanid="propertyDemo"class="cn.zzh.po.PropertyDemo">

      <!-- 使用有參數構造注入 -->

      <constructor-argname=""value="小米銷毀11"></constructor-arg>

   </bean>

測試

   @Test

   public void testPropertyDemo() {

      ApplicationContext context =new ClassPathXmlApplicationContext("ApplicationContext.xml");

      PropertyDemo propertyDemo = (PropertyDemo)context.getBean("propertyDemo");

      System.out.println(propertyDemo.getName());

   }

2)    使用set方式注入

實體建立

package cn.zzh.po;

public class Book {

   private Stringbookname;

   public void setBookname(String bookname) {

      this.bookname =bookname;

   }

   public void getbookname(){

      System.out.println(this.bookname);

   }

}

XML配置

   <!-- 使用set方法注入屬性(重點) -->

   <beanid="book"class="cn.zzh.po.Book">

      <!-- 注入屬性

         name屬性值:類裡面定義的屬性名稱

         value屬性:設定具體的值

       -->

      <propertyname="bookname"value="zzhua"></property>

   </bean>

測試代碼

@Test

   public void testgetBookName() {

      ApplicationContext context =new ClassPathXmlApplicationContext("ApplicationContext.xml");

      Book book = (Book) context.getBean("book");

      book.getbookname();

   }

3)     注入對象類型屬性(重點☆☆☆☆☆☆☆☆☆☆)

建立Dao類

package cn.zzh.dao;

public class PersionDao {

      private Stringname;

      public void setName(String name) {

         this.name =name;

      }    

      public void getName() {

         System.out.println(this.name);

      }

}

建立Service類

package cn.zzh.service;

import cn.zzh.dao.PersionDao;

public class PersionService {

   private PersionDaopersionDao;

   public PersionDao getPersionDao() {

      return persionDao;

   }

   public void setPersionDao(PersionDao persionDao) {

      this.persionDao =persionDao;

   }

   public void getname() {

      System.out.println(persionDao);

      persionDao.getName();

   }

}

XML配置

   <!-- 3)注入對象類型屬性(重點)-->

   <!-- 建立dao對象 -->

   <beanid="persionDao"class="cn.zzh.dao.PersionDao">

      <propertyname="name"value="zzhuaq"></property>

   </bean>

   <!-- 建立Service對象 -->

   <beanid="persionService"class="cn.zzh.service.PersionService">

      <!-- 注入dao對象

         name屬性:類裡面定義的屬性名稱

         ref屬性:dao配置bean标簽中id值

       -->

      <propertyname="persionDao"ref="persionDao"></property>

   </bean>

測試

   @Test

   public void testgetPersionName() {

      ApplicationContext context =new ClassPathXmlApplicationContext("ApplicationContext.xml");

      PersionService persionService = (PersionService)context.getBean("persionService");

      persionService.getname();

   }

4)    P名稱空間注入

實體類實作

package cn.zzh.dao;

public class PersionDao {

      private Stringname;

      public void setName(String name) {

         this.name =name;

      }

      public void getName() {

         System.out.println(this.name);

      }

}

XML配置

【1】

在配置檔案中添加一段限制

xmlns:p="http://www.springframework.org/schema/p",如下所示

<beansxmlns="http://www.springframework.org/schema/beans"

   xmlns:p="http://www.springframework.org/schema/p"

    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">

【2】配置bean建立對象

<!-- p名稱空間注入 -->

   <bean id="persiondao"class="cn.zzh.dao.PersionDao"p:name="hanshiyong"></bean>

測試

   @Test

   public void testpName() {

      ApplicationContext context =new ClassPathXmlApplicationContext("ApplicationContext.xml");

      PersionDao persionDao = (PersionDao)context.getBean("persiondao");

      persionDao.getName();

   }

5)    注入複雜類型屬性

主要類型有:

① 數組

② list

③ map

④ Properties

具體代碼示範

建立實體類,給實體類中添加各個複雜類型的屬性

package cn.zzh.po;

import java.util.List;

import java.util.Map;

import java.util.Properties;

public class Item {

   private Stringname;

   private String[]items;

   private List<String>lists;

   private Map<String,String>maps;

   private Propertiesproperties;

   public String getName() {

      return name;

   }

   public void setName(String name) {

      this.name =name;

   }

   public String[] getItems() {

      return items;

   }

   public void setItems(String[] items) {

      this.items =items;

   }

   public List<String> getLists() {

      return lists;

   }

   public void setLists(List<String> lists) {

      this.lists =lists;

   }

   public Map<String, String> getMaps() {

      return maps;

   }

   public void setMaps(Map<String,String> maps) {

      this.maps =maps;

   }

   public Properties getProperties() {

      return properties;

   }

   public void setProperties(Properties properties) {

      this.properties =properties;

   }

   public void test(){

      System.out.println(items.length);

      System.out.println(lists);

      System.out.println(maps);

      System.out.println(properties);

   }

}

XML配置檔案(重要)

<!-- 注入複雜類型屬性-->

   <beanid="item"class="cn.zzh.po.Item">

      <!-- 數組 -->

      <propertyname="items">

         <list>

            <value>小王</value>

            <value>小哈哈</value>

            <value>小嗎</value>

         </list>

      </property>

      <!-- list -->

      <propertyname="lists">

         <list>

            <value>111</value>

            <value>222</value>

            <value>333</value>

            <value>444</value>

         </list>

      </property>

      <!-- map -->

      <propertyname="maps">

         <map>

            <entrykey="aa"value="aa"></entry>

            <entrykey="ww"value="ww"></entry>

            <entrykey="qq"value="qq"></entry>

            <entrykey="ff"value="ff"></entry>

         </map>

      </property>

      <!-- properties -->

      <propertyname="properties">

         <props>

            <propkey="username">sa</prop>

            <propkey="pwd">123</prop>

         </props>

      </property>

   </bean>

測試

   @Test

   public void testItem() {

      ApplicationContext context =new ClassPathXmlApplicationContext("ApplicationContext.xml");

      Item item = (Item) context.getBean("item");

      item.test();

   }

6)    IOC和DI差別

IOC:控制反轉,把對象建立交給spring進行配置

DI:依賴注入,向類裡面的屬性設定值

關系:依賴注入不能單獨存在,需要在ioc基礎上完成操作。

2017/7/27

4.    Spring的bean

1)    注解的介紹

代碼裡面特殊标記,使用注解完成功能

注解寫法 @注解名稱(屬性名稱=屬性值)

注解使用在類、方法、屬性上面

2)    Spring注解開發準備

導入使用的包

 注解使用的包

建立全局配置檔案,并添加限制

限制如下(在幫助文檔/docs/spring-framework-reference/html/xsd-configuration.html中的40.2.8 the context schema章節):

<?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>      

      <!-- 開啟注解掃描

      到包裡面掃描類、方法、屬性上面的是否有注解

   -->

   <context:component-scanbase-package="cn.km"></context:component-scan>

   <!-- 掃描屬性上面的注解-->

   <!-- <context:annotation-config></context:annotation-config>-->

3)    使用注解建立對象

定義實體

package cn.km.po;

import javax.annotation.Resource;

importorg.springframework.context.annotation.Scope;

import org.springframework.stereotype.Component;

import org.springframework.stereotype.Controller;

import org.springframework.stereotype.Repository;

import org.springframework.stereotype.Service;

//下面幾種方式,效果相同(功能一樣)

//@Component

//@Component(value="user")//注:相當于<bean id="user"class="cn.km.po.User"></bean>

//@Controller         //WEB層

//@Controller(value="user")

//@Repository         //持久層

//@Repository(value="user")

//@Service           //業務層

@Service(value="user")//建立對象

@Scope(value="prototype")//建立對象是單執行個體(singletong)還是多執行個體prototype

public class User {

   public void add(){

      System.out.println("add..................");

   }

}

直接測試使用

   @Test

   public void Test(){

      ApplicationContext applicationContext =new ClassPathXmlApplicationContext("ApplicationContext.xml");

      User user =  (User) applicationContext.getBean("user");

      user.add();

   }

4)    單執行個體和多執行個體

給實體添加注解

多執行個體

//使用關鍵字@Scope建立對象是單執行個體(singleton)還是多執行個體prototype

@Scope(value="prototype") //多執行個體

@Scope(value="singleton") //單執行個體

public class User {

   public void add(){

      System.out.println("add..................");

   }

}

測試

   ApplicationContextapplicationContext =new ClassPathXmlApplicationContext("ApplicationContext.xml");

   Useruser =  (User) applicationContext.getBean("user");

   System.out.println(user);

   Useruser2 =  (User) applicationContext.getBean("user");

   System.out.println(user2);

測試輸出()

多執行個體輸出(對象位址不同,不是同一對象)

[email protected]

[email protected]

單執行個體輸出(對象位址相同,同一對象)

[email protected]

[email protected]

5)    使用注解注入屬性

① 建立實體類

② 通過注解方式建立對象,即在類名上方添加注解@Service(value="XXXXX")

③ 在需要屬性的類中添加屬性申明

④ 在屬性申明上面添加注解,注入屬性值

代碼如下:

---------------------------------------------------------------------------------------------

package cn.km.dao;

import org.springframework.stereotype.Service;

@Service(value="userDao")//注解建立UserDao對象

public class UserDao {

   public void add() {

      System.out.println("add...................");

   }

}

--------------------------------------------------

package cn.km.service;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;

importorg.springframework.stereotype.Service;

import cn.km.dao.UserDao;

@Service(value="userService")//注解方式建立對象UserService

public class UserService {

   @Resource(name="userDao")

//@Resource

//@Autowired

   private UserDaouserDao;

   public void add() {

      System.out.println("serviceadd..............");

      userDao.add();

   }

}

測試

   @Test

   public void TestUserService(){

      ApplicationContext applicationContext =new ClassPathXmlApplicationContext("ApplicationContext.xml");

      UserService userService =  (UserService)applicationContext.getBean("userService");

      System.out.println(userService);

      userService.add();

   }

----------------------------------------------------------

輸出結果

[email protected]

serviceadd..............

add...................

6)    XML和注解方式混合使用

建立實體類

package cn.km.dao;

public class BookDao {

   public void getBookName(){

      System.out.println("bookdao..............");

   }

}

package cn.km.service;

import javax.annotation.Resource;

import cn.km.dao.BookDao;

public class BookService {

   @Resource(name="bookDao") //注解給屬性注入值

   private BookDaobookDao;

   public void add(){

      System.out.println("service............");

      bookDao.getBookName();

   }

}

在XML檔案中配置建立類的對象

   <!-- 建立BookDao及BookService對象 -->

   <beanid="bookDao"class="cn.km.dao.BookDao"></bean>

   <bean id="bookService"class="cn.km.service.BookService"></bean>

在需要的類中添加屬性,并使用注解

請檢視上面代碼

測試

   @Test

   public void TestBookService(){

      ApplicationContext applicationContext =new ClassPathXmlApplicationContext("ApplicationContext.xml");

      BookService bookService =  (BookService)applicationContext.getBean("bookService");

      System.out.println(bookService);

      bookService.add();

   }

輸出結果

[email protected]

service............

bookdao..............

三、Spring的AOP

1.    Aop概述

2.    Aop底層原理

3.    Aop操作相關術語

1)       連接配接點:類裡面哪些方法可以被增強,這些方法稱為連接配接點

2)       切入點:在類裡面可以有很多的方法被增強,比如實際操作中,隻是增強了類裡面的add方法和update方法,實際增強的方法稱為切入點。

3)       通知/增強:增強的邏輯,稱為增強,比如擴充日志功能,這個日志功能稱為增強。

① 前置通知

② 後置通知

③ 異常通知

④ 最終通知

⑤ 環繞通知

4)       切面:把增強應用到具體方法上面,過程稱為切面

4.    Spring的aop操作(基于aspectj的XML方式)

在spring中進行aop操作,使用aspectJ實作

① aspectJ不是spring的一部分,和spring一起使用進行aop操作

② Spring2.0以後,新增了對aspectJ支援

使用aspectJ實作aop兩種方式

③ 基于aspectJ的XML配置

④ 基于aspectJ的注解方式

1)    Aop操作準備

① 除了導入基本的jar包之外,還需要導入aop相關jar包

aopalliance-1.0.jar

spring-aop-4.2.5.RELEASE.jar

spring-aspects-4.2.5.RELEASE.jar

Aspectjweaver jar包

② 建立spring核心配置檔案,導入aop的限制

<?xmlversion="1.0"encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="

       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

        http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsd">

</beans>

2)    使用表達式配置切入點

切入點:實際增強的方法

常用的表達式,模闆:

execution(<通路修飾符>?<傳回類型><方法名>(<參數>)<異常>)

① execution(* cn.km.aop.Book.add(..)) //切入點為add方法

② execution(* cn.km.aop.Book.*(..))  //切入點為Book類中的所有方法

③ execution(* *.*(..))                     //切入點為所有類中的所有方法

④ execution(* save*(..))           //比對所有save開頭的方法

3)    代碼驗證

① 建立實體,被增強的類

package cn.km.aop;

public class Book {

   public void add(){

      System.out.println("add...................");

   }

}

② 建立實體,切面類

package cn.km.aop;

importorg.aspectj.lang.ProceedingJoinPoint;

public class MyBook {

//前置

   public void before1(){

      System.out.println("前置............");

   }

//後置

   public void after1(){

      System.out.println("後置............");

   }

   //環繞通知

   public void around1(ProceedingJoinPointjoinPoint) throws Throwable{

      System.out.println("方法之前............");

      //執行被增強的方法

      joinPoint.proceed();

      System.out.println("方法之後............");

   }

}

③ XML配置

<?xmlversion="1.0"encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="

       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

       http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsd"><!-- aop限制 -->

   <!-- 1.配置建立對象 -->

   <beanid="book"class="cn.km.aop.Book"></bean>

   <beanid="myBook"class="cn.km.aop.MyBook"></bean>

   <!-- 2.配置aop操作 -->  

   <aop:config>

      <!-- 2.1 配置切入點

         expression:配置切入點的表達式

         id:切入點ID

      -->

      <aop:pointcutexpression="execution(* cn.km.aop.Book.*(..))"id="pointcut1"/>

      <!-- 2.2 配置切面

         ref:作為切面的類的bean的ID

         method:增強類中使用哪個方法作為字首

         pointcut-ref:切入點的ID

      -->

      <aop:aspectref="myBook">

         <aop:before method="before1" pointcut-ref="pointcut1" /> <!--前置 -->

         <aop:after-returningmethod="after1"pointcut-ref="pointcut1"/> <!--後置 -->

         <aop:aroundmethod="around1"pointcut-ref="pointcut1"/><!--環繞通知 -->

      </aop:aspect>

   </aop:config>

</beans>

④ 測試代碼

   @Test

   public void Test(){

      ApplicationContext applicationContext =new ClassPathXmlApplicationContext("ApplicationContext.xml");

      Book book = (Book) applicationContext.getBean("book");

      book.add();

   }

⑤ 測試結果輸出

前置............

方法之前............

add...................

方法之後............

後置............

5.    Log4j介紹

1)    引入jar包

commons-logging-1.2.jar

log4j-1.2.17.jar

2)    添加屬性配置檔案

配置輸出的級别

ERROR

DEBUG

INFO

WARN

6.    Spring整合web項目

一般調用流程

Action調用 Service

Service調用 Dao層

在伺服器啟動的時候,建立對象加載配置檔案

底層使用監聽器、servletContext對象

1)    在spring中配置監聽器

① 導入spring整合web項目的jar包

② 在Web.xml中進行配置如下:

 <!-- 配置監聽器

  在類ContextLoaderListener中

  -->

  <listener>

  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

 </listener>

 <!-- 指定spring配置檔案 -->

 <context-param>

  <param-name>contextConfigLocation</param-name>

  <param-value>classpath:ApplicationContext.xml</param-value>

  </context-param>

7.    Spring的aop操作(基于注解方式)

1)    準備工作

添加注解限制

http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd

2)    在spring核心配置檔案中,建立對象

   <!-- 1.配置建立對象 -->

   <beanid="book"class="cn.km.aop.Book"></bean>

   <beanid="myBook"class="cn.km.aop.MyBook"></bean>

3)    在spring核心配置檔案中,開啟aop操作

   <!-- 2.開啟aop操作 -->

   <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

4)    在增強類上面使用注解完成aop操作

① 被增強類

package cn.km.aop;

public class Book {

   public void add(){

      System.out.println("add...................");

   }

}

② 增強類

package cn.km.aop;

importorg.aspectj.lang.annotation.Aspect;

importorg.aspectj.lang.annotation.Before;

@Aspect

public class MyBook {

   @Before(value="execution(*cn.km.aop.Book.*(..))")

   public void before1(){

      System.out.println("前置............");

   }

}

5)    @AspectJ提供不同的通知類型

@Before

@AfterReturning

@Around

@AfterThrowing

@After 最終通知

8.    Spring的jdbcTemplate使用總結

1)    導入jdbc使用的jar包

2)    增加

3)    修改

4)    删除

5)    查詢

Dbutils實作

jdbcTemplate實作查詢,有接口RowMapper,

jdbcTemplate針對這個接口沒有提供實作類,得到不同的類型的資料需要自己進行資料封裝

① 查詢傳回某個值

   @Test

   public void testCount(){

      //設定資料庫資訊

      DriverManagerDataSource dataSource =new DriverManagerDataSource();

      dataSource.setDriverClassName("com.mysql.jdbc.Driver");

      dataSource.setUrl("jdbc:mysql:///spring_jdbc_0802");

      dataSource.setUsername("root");

      dataSource.setPassword("root");

      //建立jdbcTemplate對象

      JdbcTemplate jdbcTemplate =new JdbcTemplate(dataSource);

      //調用方法得到記錄數

      String sql = "select count(*) fromuserInfo";

      //調用jdbcTemplate方法

      int count = jdbcTemplate.queryForObject(sql,Integer.class);

      System.out.println(count);

   }

② 查詢傳回對象

@Test

   public void testObject(){

      //設定資料庫資訊

      DriverManagerDataSource dataSource =new DriverManagerDataSource();

      dataSource.setDriverClassName("com.mysql.jdbc.Driver");

      dataSource.setUrl("jdbc:mysql:///spring_jdbc_0802");

      dataSource.setUsername("root");

      dataSource.setPassword("root");

      //建立jdbcTemplate對象

      JdbcTemplate jdbcTemplate =new JdbcTemplate(dataSource);

      //調用方法得到記錄數

      String sql = "select * from userInfowhere username=?";

      //調用jdbcTemplate方法

      //第二個參數是RowMapper,需要自己實作接口,做資料封裝

      User user = jdbcTemplate.queryForObject(sql,new MyRowMapper(),"Bob");

      System.out.println(user);

   }

自定義類

class MyRowMapperimplements RowMapper<User>{

   @Override

   public User mapRow(ResultSetrs, intnum) throws SQLException {

      String username = rs.getString("username");

      String password = rs.getString("password");

      User user = new User();

      user.setUsername(username);

      user.setPassword(password);

      return user;

   }

}

③ 查詢傳回List集合

Sql語句

RowMapper接口,自己寫類進行封裝

可變參數

   @Test

   public void testList(){

      //設定資料庫資訊

      DriverManagerDataSource dataSource =new DriverManagerDataSource();

      dataSource.setDriverClassName("com.mysql.jdbc.Driver");

      dataSource.setUrl("jdbc:mysql:///spring_jdbc_0802");

      dataSource.setUsername("root");

      dataSource.setPassword("root");

      //建立jdbcTemplate對象

      JdbcTemplate jdbcTemplate =new JdbcTemplate(dataSource);

      //調用方法得到記錄數

      String sql = "select * fromuserInfo";

      //調用jdbcTemplate方法

      //第二個參數是RowMapper,需要自己實作接口,做資料封裝

      //後面可以跟參數即sql語句中的參數

      List<User> list =jdbcTemplate.query(sql,new MyRowMapper());

      System.out.println(list);

   }

使用的自定的類與上面查詢對象一樣:

class MyRowMapperimplements RowMapper<User>{

   @Override

   public User mapRow(ResultSetrs, intnum) throws SQLException {

      String username = rs.getString("username");

      String password = rs.getString("password");

      User user = new User();

      user.setUsername(username);

      user.setPassword(password);

      return user;

   }

}

9.    Spring配置連接配接池和dao使用jdbcTemplate

1)  Spring配置c3p0連接配接池

① 導入jar包

Jar包mchange-commons-java-0.2.3.4.jar

② 建立spring配置檔案

代碼實作配置如下:

      ComboPooledDataSource dataSource =new ComboPooledDataSource();

      dataSource.setDriverClass("com.mysql.jdbc.Driver");

      dataSource.setJdbcUrl("jdbc:mysql:///spring_jdbc_0802");

      dataSource.setUser("root");

      dataSource.setPassword("root");

把代碼在配置檔案中進行配置

   <!-- 建立c3p0連接配接池 -->

   <beanid="dataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource">

      <propertyname="driverClass"value="com.mysql.jdbc.Driver"></property>

      <propertyname="jdbcUrl"value="jdbc:mysql:///spring_jdbc_0802"></property>

      <propertyname="user"value="root"></property>

      <propertyname="password"value="root"></property>

   </bean>

2)  Dao使用jdbcTemplate

① 建立service和dao,配置service和dao對象,在service注入dao對象

   <!-- 建立Service和Dao對象,在service中注入dao對象 -->

   <beanid="userService"class="cn.km.service.UserService">

      <propertyname="userDao"ref="userDao"></property>

   </bean>

   <bean id="userDao" class="cn.km.dao.UserDao">

② 建立jdbcTemplate對象,把模闆對象注入到dao裡面

<beanid="userDao"class="cn.km.dao.UserDao">

      <!-- 在userDao類中注入jdbcTemplate對象-->

      <propertyname="jdbcTemplate"ref="jdbcTemplate"></property>

   </bean>

   <!-- 建立jdbcTemplate對象 -->

   <bean id="jdbcTemplate"class="org.springframework.jdbc.core.JdbcTemplate">

③ 向jdbcTemplate對象中注入dataSource

<!-- 建立jdbcTemplate對象 -->

   <beanid="jdbcTemplate"class="org.springframework.jdbc.core.JdbcTemplate">

      <!-- 把dataSource傳遞到模闆對象裡面-->

      <propertyname="dataSource"ref="dataSource"></property>

   </bean>

10.        Spring事物管理

1)    事物相關的概念

一組操作,一個失敗,整體失敗。

2)    Spring事務管理API

① Spring事務管理有兩種方式

第一種 程式設計式事務管理(不使用)

第二種 申明式事務管理

基于XML配置檔案的

基于注解方式

接口PlatformTransactionManager為事務管理器

② Spring針對不同的dao層架構,提供不同的實作類

org.springframework.jdbc.datasource.DataSourceTransactionManager 使用Spring jdbc或ibatis進行持久化資料時使用

③ 配置事務管理器

④ 使用事務的執行個體

使用XML配置方式

a.        建立資料表(sql語句)

USE [kmOA]

GO

SET ANSI_NULLSON

GO

SET QUOTED_IDENTIFIERON

GO

CREATE TABLE[dbo].[userinfo](

         [id] [int] NULL,

         [name] [nvarchar](50)NULL,

         [salary][int]NULL

) ON[PRIMARY]

GO

b.       建立Dao層和Service層

Dao層代碼

package cn.km.dao;

import org.springframework.jdbc.core.JdbcTemplate;

public class UserDao {

   private JdbcTemplatejdbcTemplate;

   public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {

      this.jdbcTemplate =jdbcTemplate;

   }

   private int id;

   private Stringname;

   private int salary;

   public int getId() {

      return id;

   }

   public void setId(intid) {

      this.id =id;

   }

   public String getName() {

      return name;

   }

   public void setName(String name) {

      this.name =name;

   }

   public int getSalary() {

      return salary;

   }

   public void setSalary(intsalary) {

      this.salary =salary;

   }

}

Service層代碼

package cn.km.service;

import cn.km.dao.UserDao;

public class UserService {

   private UserDaouserDao;

   public void setUserDao(UserDao userDao) {

      this.userDao =userDao;

   }

}

c.        向Service層注入Dao對象

首先在Service類中添加Dao屬性,生成set方法

然後在ApplicationContext.xml檔案中添加如下:

<!-- 建立Service和Dao對象,在service中注入dao對象 -->

   <beanid="userService"class="cn.km.service.UserService">

      <propertyname="userDao"ref="userDao"></property>

   </bean>

   <beanid="userDao"class="cn.km.dao.UserDao">

d.       Dao對象中注入jdbcTemplate對象

<beanid="userDao"class="cn.km.dao.UserDao">

      <!-- 在userDao類中注入jdbcTemplate對象-->

      <propertyname="jdbcTemplate"ref="jdbcTemplate"></property>

   </bean>

   <!-- 建立jdbcTemplate對象 -->

   <beanid="jdbcTemplate"class="org.springframework.jdbc.core.JdbcTemplate">

e.        jdbcTemplate對象中注入dataSource對象

   <!-- 建立jdbcTemplate對象 -->

   <beanid="jdbcTemplate"class="org.springframework.jdbc.core.JdbcTemplate">

      <!-- 把dataSource傳遞到模闆對象裡面-->

      <propertyname="dataSource"ref="dataSource"></property>

   </bean>

f.         建立dataSource對象

   <!-- 建立c3p0連接配接池 -->

   <beanid="dataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource">

      <propertyname="driverClass"value="com.mysql.jdbc.Driver"></property>

      <propertyname="jdbcUrl"value="jdbc:mysql:///spring_jdbc_0802"></property>

      <propertyname="user"value="root"></property>

      <propertyname="password"value="root"></property>

</bean>

g.        配置事務(重點)

使用注解方式

11.        附錄

1)    Spring全局配置檔案比較全的限制

<?xml version="1.0"encoding="UTF-8"?>

<beansxmlns="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.xsd

       http://www.springframework.org/schema/context

              http://www.springframework.org/schema/context/spring-context.xsd

              http://www.springframework.org/schema/aop

              http://www.springframework.org/schema/aop/spring-aop.xsd           

              http://www.springframework.org/schema/tx

              http://www.springframework.org/schema/tx/spring-tx.xsd">

</beans>

12.        問題彙集

缺少jar包aspectjweaver  jar包