1. 程式人生 > >Spring筆記02

Spring筆記02

不同的 ole test spring整合 註解 ack 3.2 會有 red

Spring筆記02

1. Spring整合連接池

1.1 Spring整合C3P0

  • 在工程中導入c3p0連接池需要的包com.springsource.com.mchange.v2.c3p0-0.9.1.2.jar

  • c3p0的硬編碼方式

    @Test //自己new對象,自己設置屬性
      public void test() throws Exception {
          ComboPooledDataSource dataSource = new ComboPooledDataSource();
          //設置驅動
          dataSource.setDriverClass("com.mysql.jdbc.Driver");
          //設置地址
          dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/hibernate");
          //設置用戶名
          dataSource.setUser("root");
          //設置密碼
          dataSource.setPassword("2626");
          //獲取鏈接池連接對象
          Connection con = dataSource.getConnection();
          System.out.println(con);
          //[email protected]
      }
  • Spring整合c3p0連接池

  • 配置文件

    <!-- c3p0 -->
      <bean id="C3P0" class="com.mchange.v2.c3p0.ComboPooledDataSource">
          <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
          <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/hibernate"></property>
          <property name="user" value="root"></property>
          <property name="password" value="2626"></property>
      </bean>
  • 測試

    @Test //Spring的IOC+DI替代以上硬編碼的方式
      public void test2() throws SQLException {
          ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
          DataSource dataSource = (DataSource) context.getBean("C3P0");
          Connection con = dataSource.getConnection();
          System.out.println(con);
          //[email protected]
      }

1.2 Spring整合DBCP

  • 導入DBCP連接池需要的包com.springsource.org.apache.commons.dbcp-1.2.2.osgi.jar和com.springsource.org.apache.commons.pool-1.5.3.jar

  • DBCP硬編碼方式

    @Test //DBCP的硬編碼方式
      public void test3() throws SQLException {
          BasicDataSource dataSource = new BasicDataSource();
          dataSource.setDriverClassName("com.mysql.jdbc.Driver");
          dataSource.setUrl("jdbc:mysql://localhost:3306/hibernate");
          dataSource.setUsername("root");
          dataSource.setPassword("2626");
          Connection con = dataSource.getConnection();
          System.out.println(con);
          //jdbc:mysql://localhost:3306/hibernate, [email protected], MySQL-AB JDBC Driver
      }
  • Spring整合DBCP

  • 配置文件

    <!-- DBCP -->
      <bean id="DBCP" class="org.apache.tomcat.dbcp.dbcp.BasicDataSource">
          <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
          <property name="url" value="jdbc:mysql://localhost:3306/hibernate"></property>
          <property name="username" value="root"></property>
          <property name="password" value="2626"></property>
      </bean>
  • 測試

    @Test
      public void test4() throws SQLException {
          ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
          DataSource dataSource = (DataSource) context.getBean("DBCP");
          Connection con = dataSource.getConnection();
          System.out.println(con);
          //jdbc:mysql://localhost:3306/hibernate, [email protected], MySQL-AB JDBC Driver
      }

1.3 最終版

  • 最終版使用propertie配置文件,Spring加載properties文件

  • Spring提供了一個標簽可以加載外部的properties文件內容

  • 導入context的名稱空間和約束後,xml文件中才會有提示,這個約束在/spring-framework-4.2.4.RELEASE/docs/spring-framework-reference/html/xsd-configuration.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>
  • 導入約束後配置xml

    <context:property-placeholder location="classpath:jdbc.properties"/>
    
      <!-- DBCP -->
      <bean id="DBCP" class="org.apache.tomcat.dbcp.dbcp.BasicDataSource">
          <property name="driverClassName" value="${jdbc.driver}"></property>
          <property name="url" value="${jdbc.url}"></property>
          <property name="username" value="${jdbc.username}"></property>
          <property name="password" value="${jdbc.password}"></property>
      </bean>
  • 測試

    @Test
      public void test4() throws SQLException {
          ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
          DataSource dataSource = (DataSource) context.getBean("DBCP");
          Connection con = dataSource.getConnection();
          System.out.println(con);
          //jdbc:mysql://localhost:3306/hibernate, [email protected], MySQL-AB JDBC Driver
      }
  • jdbc.properties配置文件可以配置不同的數據庫,切換方便。

2. 基於註解的IOC配置

  • 註解配置和xml配置要實現的功能都是一樣的,都是要降低程序間的耦合。只是配置形式不一樣。至於是使用xml還是註解,實際的開發過程中,每家公司有不同的習慣。

2.1 導包

  • 拷貝必備包到lib目錄下。基於註解的配置中,需要加入一個aop的jar包。

2.2 配置文件

  • 基於註解的配置文件,導入約束時需要多導入一個context名稱空間下的約束。約束的位置可以在約束的位置在:

    ? ..\spring-framework-4.2.4.RELEASE\docs\spring-framework-reference\html\xsd-configuration.html中找到

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:context="http://www.springframework.org/schema/context"
           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
                  http://www.springframework.org/schema/context
                      http://www.springframework.org/schema/context/spring-context.xsd ">
    </beans>

2.3 開啟註解掃描器

  • 在配置文件中開啟註解掃描器

    <!-- 開啟註解掃描器
          com.itzhouq:包含自己以及自己下面的所有子包
     -->
    <context:component-scan base-package="com.itzhouq"></context:component-scan>
    
  • 告知Spring框架,在讀取配置文件,創建容器時,依據註解創建對象,並存入容器中

2.4 使用註解

  • 要創建UserDaoImpl對象,在類上使用@Component註解。只要定義在類上,那麽註解掃描器只要一掃描到就會創建該類的實例對象,放入Spring容器中。

    package com.itzhouq.daoImpl;
    
    import org.springframework.stereotype.Component;
    
    import com.itzhouq.dao.UserDao;
    
    @Component("userDao") //<bean id="userDao" class="com.itzhouq.daoImpl.UserDaoImpl"></bean>
    public class UserDaoImpl implements UserDao{
    
      @Override
      public void save() {
          System.out.println("操作數據庫,保存用戶的數據");
      }
    }
  • 要創建的對象UserServiceImpl,在類上使用註解,在屬性上使用註解

  • @value("屬性值"):定義在屬性字段上,針對的是基本數據類型和String類型。如果使用了這個註解,該屬性的set方法可以省略不寫。

  • @Autowired:定義在屬性字段上,針對的是對象類型。自動按照類型註入,當使用註解註入屬性時,set方法可以省略。它只能註入其他bean類型。當有多個類型匹配時,使用要註解的對象變量名作為bean的id,在Spring容器查找,找到了也可以註入成功,找不到就報錯。

  • @Qualifier("對象屬性id"):定義在屬性字段上。在自動按照類型註入的基礎上,再按照Bean的id註入。他在給字段註入時,不能獨立使用,必須和@Autowired一起使用。但是給方法參數註入時,可以獨立使用。

    package com.itzhouq.serviceImpl;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    
    import com.itzhouq.dao.UserDao;
    import com.itzhouq.daoImpl.UserDaoImpl;
    import com.itzhouq.service.UserService;
    
    @Component("userService") //<bean id="UserService" class="com.itzhouq.serviceImpl.UserServiceImpl">
    public class UserServiceImpl implements UserService {
      @Value("要開始訪問dao了") //<property name="name" value="要開始訪問dao了"></property>
      private String name;    //使用註解,可以不需要set方法,相當於直接賦值
    
      @Autowired  //對象類型:自動去Spring容器中找有沒有該類型(UserDao)的實例對象  如果有直接賦值
        @Qualifier("userDao")
      private UserDao userDao;
      public void setUserDao(UserDao userDao) {
          this.userDao = userDao;
      }
    
      @Override
      public void save() {
          System.out.println(name);
          //調用dao
          userDao.save();
      }
    }
  • 測試

    @Test
      public void test() {
          ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
          UserService userService = (UserService) context.getBean("userService");
          userService.save();
          //要開始訪問dao了
          //操作數據庫,保存用戶的數據
      }

2.5了解的幾個註解

  • @Scope("singleton") / @Scope("prototype"):定義在類上,用於指定該類是單實例還是多實例
    • 一般action/web層為多實例,service和dao層為單實例
  • @PostConstruct:定義在方法上,用於配置初始化方法
  • @PreDestroy:定義在方法上,用於配置銷毀的方法

3. Spring整合JUnit

技術分享圖片

3.1 導入包

  • spring-aop-4.2.4.RELEASE.jar
  • spring-test-4.2.4.RELEASE.jar
  • junit.jar

3.2 編寫測試類

package com.itzhouq.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.itzhouq.service.UserService;

//1. 告訴Spring配置文件的位置
//2. 告訴Spring誰去加載配置文件
@ContextConfiguration(value="classpath:applicationContext.xml")
@RunWith(value=SpringJUnit4ClassRunner.class)
public class SpringJunit {
    @Autowired
    private UserService userService;
    
    @Test
    public void test() {
        userService.save();
//      要開始訪問dao了
//      操作數據庫,保存用戶的數據
    }
}

3.3 註解

  • 使用@RunWith註解替換原有運行器
  • 使用@ContextConfiguration指定spring配置文件的位置
  • 使用@Autowired給測試類中的變量註入數據

Spring筆記02