天天看點

spring讀取properties配置檔案_Spring-1

spring共四天
第一天:spring架構的概述以及spring中基于XML的IOC配置
第二天:spring中基于注解的IOC和ioc的案例
第三天:spring中的aop和基于XML以及注解的AOP配置
第四天:spring中的JdbcTemlate以及Spring事務控制
-----------------------------------------------------
1、spring的概述
	spring是什麼
	spring的兩大核心
	spring的發展曆程和優勢
	spring體系結構
2、程式的耦合及解耦
	曾經案例中問題
	工廠模式解耦
3、IOC概念和spring中的IOC
	spring中基于XML的IOC環境搭建
4、依賴注入(Dependency Injection)
           

1 Spring第一天

1.1 程式耦合問題
package com.iteima.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * 程式的耦合
 *      耦合:程式間的依賴關系
 *          包括:
 *              類之間的依賴
 *              方法間的依賴
 *      解耦:
 *          降低程式間的依賴關系
 *      實際開發中:
 *          應該做到:編譯期不依賴,運作時才依賴
 *      解耦的思路:
 *          第一步:使用反射來建立對象,而避免使用new關鍵字
 *          第二步:通過讀取配置檔案來擷取要建立的對象全限定類名
 */
public class JdbcDemo1 {
    public static void main(String[] args) throws Exception {
        //1.注冊驅動
//        DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        Class.forName("com.mysql.jdbc.Driver");
        //2.擷取連接配接
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/eesy", "root", "1234");
        //3.擷取操作資料庫的預處理對象
        PreparedStatement pstm = conn.prepareStatement("select * from account");
        //4.執行SQL,得到結果集
        ResultSet rs = pstm.executeQuery();
        //5.周遊結果集
        while(rs.next()) {
            System.out.println(rs.getString("name"));
        }
        //6.釋放資源
        rs.close();
        pstm.close();
        conn.close();
    }
}
           
1.2 解耦
  • IAccountDao.java;
package com.itheima.dao;

/**
 * 賬戶的持久層接口
 */
public interface IAccountDao {
    /**
     * 模拟儲存賬戶
     */
    void saveAccount();
}
           
  • AccountDaoImpl.java;
package com.itheima.dao.impl;

import com.itheima.dao.IAccountDao;

/**
 * 賬戶的持久層實作類
 */
public class AccountDaoImpl implements IAccountDao {
    public void saveAccount() {
        System.out.println("儲存了賬戶");
    }
}
           
  • IAccountService.java;
package com.itheima.service;

/**
 * 賬戶業務層的接口
 */
public interface IAccountService {
    /**
     * 模拟儲存賬戶
     */
    void saveAccount();
}
           
  • AccountServiceImpl.java;
package com.itheima.service.impl;

import com.itheima.dao.IAccountDao;
import com.itheima.factory.BeanFactory;
import com.itheima.service.IAccountService;

/**
 * 賬戶的業務層實作類
 */
public class AccountServiceImpl implements IAccountService {
//    private IAccountDao accountDao = new AccountDaoImpl();
    private IAccountDao accountDao = (IAccountDao)BeanFactory.getBean("accountDao");
//    private int i = 1;

    public void saveAccount() {
        int i = 1;
        accountDao.saveAccount();
        System.out.println(i);
        i++;
    }
}
           
  • Client.java;
package com.itheima.ui;

import com.itheima.factory.BeanFactory;
import com.itheima.service.IAccountService;

/**
 * 模拟一個表現層,用于調用業務層
 */
public class Client {
    public static void main(String[] args) {
        //IAccountService as = new AccountServiceImpl();
        for(int i = 0; i < 5; i++) {
            IAccountService as = (IAccountService) BeanFactory.getBean("accountService");
            System.out.println(as);
            as.saveAccount();
        }
    }
}
           
  • BeanFactory.java;
package com.itheima.factory;

import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 一個建立Bean對象的工廠
 * Bean:在計算機英語中,有可重用元件的含義
 * JavaBean:用java語言編寫的可重用元件
 *      javabean > 實體類
 *   它就是建立我們的service和dao對象的
 *   第一個:需要一個配置檔案來配置我們的service和dao
 *           配置的内容:唯一辨別=全限定類名(key=value)
 *   第二個:通過讀取配置檔案中配置的内容,反射建立對象
 *   我的配置檔案可以是xml也可以是properties
 */
public class BeanFactory {
    //定義一個Properties對象
    private static Properties props;
    //定義一個Map,用于存放我們要建立的對象,我們把它稱之為容器
    private static Map<String, Object> beans;
    //使用靜态代碼塊為Properties對象指派
    static {
        try {
            //執行個體化對象
            props = new Properties();
            //擷取properties檔案的流對象
            InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
            props.load(in);
            //執行個體化容器
            beans = new HashMap<String, Object>();
            //取出配置檔案中所有的Key
            Enumeration keys = props.keys();
            //周遊枚舉
            while (keys.hasMoreElements()) {
                //取出每個Key
                String key = keys.nextElement().toString();
                //根據key擷取value
                String beanPath = props.getProperty(key);
                //反射建立對象
                Object value = Class.forName(beanPath).newInstance();
                //把key和value存入容器中
                beans.put(key, value);
            }
        } catch (Exception e) {
            throw new ExceptionInInitializerError("初始化properties失敗!");
        }
    }

    /**
     * 根據bean的名稱擷取對象
     */
    public static Object getBean(String beanName) {
        return beans.get(beanName);
    }

    /**
     * 根據Bean的名稱擷取bean對象
    public static Object getBean(String beanName) {
        Object bean = null;
        try {
            String beanPath = props.getProperty(beanName);
//            System.out.println(beanPath);
            bean = Class.forName(beanPath).newInstance();//每次都會調用預設構造函數建立對象
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bean;
    }*/
}
           
  • Bean.properties;
accountService=com.itheima.service.impl.AccountServiceImpl
accountDao=com.itheima.dao.impl.AccountDaoImpl
           
  • 單例與多例;
spring讀取properties配置檔案_Spring-1
1.3 IOC
  • IAccountDao.java;
package com.itheima.dao;

/**
 * 賬戶的持久層接口
 */
public interface IAccountDao {
    /**
     * 模拟儲存賬戶
     */
    void saveAccount();
}
           
  • AccountDaoImpl.java;
package com.itheima.dao.impl;

import com.itheima.dao.IAccountDao;

/**
 * 賬戶的持久層實作類
 */
public class AccountDaoImpl implements IAccountDao {
    public void saveAccount(){
        System.out.println("儲存了賬戶");
    }
}
           
  • IAccountService.java;
package com.itheima.service;

/**
 * 賬戶業務層的接口
 */
public interface IAccountService {
    /**
     * 模拟儲存賬戶
     */
    void saveAccount();
}
           
  • AccountServiceImpl.java;
package com.itheima.service.impl;

import com.itheima.dao.IAccountDao;
import com.itheima.service.IAccountService;

/**
 * 賬戶的業務層實作類
 */
public class AccountServiceImpl implements IAccountService {
    private IAccountDao accountDao ;

    public AccountServiceImpl(){
        System.out.println("對象建立了");
    }

    public void  saveAccount(){
        accountDao.saveAccount();
    }
}
           
  • Client.java;
package com.itheima.ui;

import com.itheima.dao.IAccountDao;
import com.itheima.service.IAccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 模拟一個表現層,用于調用業務層
 */
public class Client {
    /**
     * 擷取spring的Ioc核心容器,并根據id擷取對象
     * ApplicationContext的三個常用實作類:
     *      ClassPathXmlApplicationContext:它可以加載類路徑下的配置檔案,要求配置檔案必須在類路徑下,不在的話,加載不了,(更常用)
     *      FileSystemXmlApplicationContext:它可以加載磁盤任意路徑下的配置檔案(必須有通路權限)
     *      AnnotationConfigApplicationContext:它是用于讀取注解建立容器的,是明天的内容
     * 核心容器的兩個接口引發出的問題:
     *  ApplicationContext:     單例對象适用              采用此接口
     *      它在建構核心容器時,建立對象采取的政策是采用立即加載的方式,也就是說,隻要一讀取完配置檔案馬上就建立配置檔案中配置的對象
     *  BeanFactory:            多例對象使用
     *      它在建構核心容器時,建立對象采取的政策是采用延遲加載的方式,也就是說,什麼時候根據id擷取對象了,什麼時候才真正的建立對象
     */
    public static void main(String[] args) {
        //1.擷取核心容器對象
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//        ApplicationContext ac = new FileSystemXmlApplicationContext("C:UserszhyDesktopbean.xml");
        //2.根據id擷取Bean對象
        IAccountService as  = (IAccountService)ac.getBean("accountService");
        IAccountDao adao = ac.getBean("accountDao",IAccountDao.class);
        System.out.println(as);
        System.out.println(adao);
        as.saveAccount();
        //--------BeanFactory----------
//        Resource resource = new ClassPathResource("bean.xml");
//        BeanFactory factory = new XmlBeanFactory(resource);
//        IAccountService as  = (IAccountService)factory.getBean("accountService");
//        System.out.println(as);
    }
}
           
  • bean.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--把對象的建立交給spring來管理-->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean>
    <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl"></bean>
</beans>
           
1.4 Spring三種建立Bean的方式
  • IAccountService.java;
package com.itheima.service;

/**
 * 賬戶業務層的接口
 */
public interface IAccountService {
    /**
     * 模拟儲存賬戶
     */
    void saveAccount();
}
           
  • AccountServiceImpl.java;
package com.itheima.service.impl;

import com.itheima.service.IAccountService;

/**
 * 賬戶的業務層實作類
 */
public class AccountServiceImpl implements IAccountService {
    public AccountServiceImpl() {
        System.out.println("對象建立了");
    }

    public void saveAccount() {
        System.out.println("service中的saveAccount方法執行了。。。");
    }

    public void init() {
        System.out.println("對象初始化了。。。");
    }

    public void destroy() {
        System.out.println("對象銷毀了。。。");
    }
}
           
  • StaticFactory.java;
package com.itheima.factory;

import com.itheima.service.IAccountService;
import com.itheima.service.impl.AccountServiceImpl;

/**
 * 模拟一個工廠類(該類可能是存在于jar包中的,我們無法通過修改源碼的方式來提供預設構造函數)
 */
public class StaticFactory {
    public static IAccountService getAccountService() {
        return new AccountServiceImpl();
    }
}
           
  • InstanceFactory.java;
package com.itheima.factory;

import com.itheima.service.IAccountService;
import com.itheima.service.impl.AccountServiceImpl;

/**
 * 模拟一個工廠類(該類可能是存在于jar包中的,我們無法通過修改源碼的方式來提供預設構造函數)
 */
public class InstanceFactory {
    public IAccountService getAccountService() {
        return new AccountServiceImpl();
    }
}
           
  • Client.java;
package com.itheima.ui;

import com.itheima.service.IAccountService;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 模拟一個表現層,用于調用業務層
 */
public class Client {
    public static void main(String[] args) {
        //1.擷取核心容器對象
//        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.根據id擷取Bean對象
        IAccountService as = (IAccountService)ac.getBean("accountService");
        as.saveAccount();
        //手動關閉容器
        ac.close();
    }
}
           
  • bean.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--把對象的建立交給spring來管理-->
    <!--spring對bean的管理細節
        1.建立bean的三種方式
        2.bean對象的作用範圍
        3.bean對象的生命周期
    -->

    <!--建立Bean的三種方式 -->
    <!-- 第一種方式:使用預設構造函數建立。
            在spring的配置檔案中使用bean标簽,配以id和class屬性之後,且沒有其他屬性和标簽時。
            采用的就是預設構造函數建立bean對象,此時如果類中沒有預設構造函數,則對象無法建立。
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean>
    -->

    <!-- 第二種方式: 使用普通工廠中的方法建立對象(使用某個類中的方法建立對象,并存入spring容器)
    <bean id="instanceFactory" class="com.itheima.factory.InstanceFactory"></bean>
    <bean id="accountService" factory-bean="instanceFactory" factory-method="getAccountService"></bean>
    -->

    <!-- 第三種方式:使用工廠中的靜态方法建立對象(使用某個類中的靜态方法建立對象,并存入spring容器)
    <bean id="accountService" class="com.itheima.factory.StaticFactory" factory-method="getAccountService"></bean>
    -->

    <!-- bean的作用範圍調整
        bean标簽的scope屬性:
            作用:用于指定bean的作用範圍
            取值:常用的就是單例的和多例的
                singleton:單例的(預設值)
                prototype:多例的
                request:作用于web應用的請求範圍
                session:作用于web應用的會話範圍
                global-session:作用于叢集環境的會話範圍(全局會話範圍),當不是叢集環境時,它就是session
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl" scope="prototype"></bean>
    -->

    <!-- bean對象的生命周期
            單例對象
                出生:當容器建立時對象出生
                活着:隻要容器還在,對象一直活着
                死亡:容器銷毀,對象消亡
                總結:單例對象的生命周期和容器相同
            多例對象
                出生:當我們使用對象時spring架構為我們建立
                活着:對象隻要是在使用過程中就一直活着。
                死亡:當對象長時間不用,且沒有别的對象引用時,由Java的垃圾回收器回收
     -->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"
          scope="prototype" init-method="init" destroy-method="destroy"></bean>
</beans>
           
1.5 Spring依賴注入
  • AccountServiceImpl.java;
package com.itheima.service.impl;

import com.itheima.service.IAccountService;
import java.util.Date;

/**
 * 賬戶的業務層實作類
 */
public class AccountServiceImpl implements IAccountService {
    //如果是經常變化的資料,并不适用于注入的方式
    private String name;
    private Integer age;
    private Date birthday;

    public AccountServiceImpl(String name, Integer age, Date birthday) {
        this.name = name;
        this.age = age;
        this.birthday = birthday;
    }

    public void saveAccount() {
        System.out.println("service中的saveAccount方法執行了。。。" + name + "," + age + "," + birthday);
    }
}
           
  • AccountServiceImpl2.java;
package com.itheima.service.impl;

import com.itheima.service.IAccountService;
import java.util.Date;

/**
 * 賬戶的業務層實作類
 */
public class AccountServiceImpl2 implements IAccountService {
    //如果是經常變化的資料,并不适用于注入的方式
    private String name;
    private Integer age;
    private Date birthday;

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public void saveAccount() {
        System.out.println("service中的saveAccount方法執行了。。。" + name + "," + age + "," + birthday);
    }
}
           
  • AccountServiceImpl3.java;
package com.itheima.service.impl;

import com.itheima.service.IAccountService;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.Map;

/**
 * 賬戶的業務層實作類
 */
public class AccountServiceImpl3 implements IAccountService {
    private String[] myStrs;
    private List<String> myList;
    private Set<String> mySet;
    private Map<String, String> myMap;
    private Properties myProps;

    public void setMyStrs(String[] myStrs) {
        this.myStrs = myStrs;
    }

    public void setMyList(List<String> myList) {
        this.myList = myList;
    }

    public void setMySet(Set<String> mySet) {
        this.mySet = mySet;
    }

    public void setMyMap(Map<String, String> myMap) {
        this.myMap = myMap;
    }

    public void setMyProps(Properties myProps) {
        this.myProps = myProps;
    }

    public void saveAccount(){
        System.out.println(Arrays.toString(myStrs));
        System.out.println(myList);
        System.out.println(mySet);
        System.out.println(myMap);
        System.out.println(myProps);
    }
}
           
  • IAccountService.java;
package com.itheima.service;

/**
 * 賬戶業務層的接口
 */
public interface IAccountService {
    /**
     * 模拟儲存賬戶
     */
    void saveAccount();
}
           
  • Client.java;
package com.itheima.ui;

import com.itheima.service.IAccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 模拟一個表現層,用于調用業務層
 */
public class Client {
    public static void main(String[] args) {
        //1.擷取核心容器對象
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.根據id擷取Bean對象
//        IAccountService as = (IAccountService)ac.getBean("accountService");
//        as.saveAccount();
//        IAccountService as = (IAccountService)ac.getBean("accountService2");
//        as.saveAccount();
        IAccountService as = (IAccountService)ac.getBean("accountService3");
        as.saveAccount();
    }
}
           
  • bean.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- spring中的依賴注入
        依賴注入:
            Dependency Injection
        IOC的作用:
            降低程式間的耦合(依賴關系)
        依賴關系的管理:
            以後都交給spring來維護
        在目前類需要用到其他類的對象,由spring為我們提供,我們隻需要在配置檔案中說明
        依賴關系的維護:
            就稱之為依賴注入
         依賴注入:
            能注入的資料:有三類
                基本類型和String
                其他bean類型(在配置檔案中或者注解配置過的bean)
                複雜類型/集合類型
             注入的方式:有三種
                第一種:使用構造函數提供
                第二種:使用set方法提供
                第三種:使用注解提供(明天的内容)
     -->

    <!--構造函數注入:
        使用的标簽:constructor-arg
        标簽出現的位置:bean标簽的内部
        标簽中的屬性
            type:用于指定要注入的資料的資料類型,該資料類型也是構造函數中某個或某些參數的類型
            index:用于指定要注入的資料給構造函數中指定索引位置的參數指派。索引的位置是從0開始
            name:用于指定給構造函數中指定名稱的參數指派                                        常用的
            =============以上三個用于指定給構造函數中哪個參數指派===============================
            value:用于提供基本類型和String類型的資料
            ref:用于指定其他的bean類型資料,它指的就是在spring的Ioc核心容器中出現過的bean對象
        優勢:
            在擷取bean對象時,注入資料是必須的操作,否則對象無法建立成功
        弊端:
            改變了bean對象的執行個體化方式,使我們在建立對象時,如果用不到這些資料,也必須提供
    -->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
        <constructor-arg name="name" value="泰斯特"></constructor-arg>
        <constructor-arg name="age" value="18"></constructor-arg>
        <constructor-arg name="birthday" ref="now"></constructor-arg>
    </bean>

    <!-- 配置一個日期對象 -->
    <bean id="now" class="java.util.Date"></bean>
    
    <!-- set方法注入                更常用的方式
        涉及的标簽:property
        出現的位置:bean标簽的内部
        标簽的屬性
            name:用于指定注入時所調用的set方法名稱
            value:用于提供基本類型和String類型的資料
            ref:用于指定其他的bean類型資料。它指的就是在spring的Ioc核心容器中出現過的bean對象
        優勢:
            建立對象時沒有明确的限制,可以直接使用預設構造函數
        弊端:
            如果有某個成員必須有值,則擷取對象是有可能set方法沒有執行
    -->
    <bean id="accountService2" class="com.itheima.service.impl.AccountServiceImpl2">
        <property name="name" value="TEST" ></property>
        <property name="age" value="21"></property>
        <property name="birthday" ref="now"></property>
    </bean>

    <!-- 複雜類型的注入/集合類型的注入
        用于給List結構集合注入的标簽:
            list array set
        用于個Map結構集合注入的标簽:
            map  props
        結構相同,标簽可以互換
    -->
    <bean id="accountService3" class="com.itheima.service.impl.AccountServiceImpl3">
        <property name="myStrs">
            <set>
                <value>AAA</value>
                <value>BBB</value>
                <value>CCC</value>
            </set>
        </property>

        <property name="myList">
            <array>
                <value>AAA</value>
                <value>BBB</value>
                <value>CCC</value>
            </array>
        </property>

        <property name="mySet">
            <list>
                <value>AAA</value>
                <value>BBB</value>
                <value>CCC</value>
            </list>
        </property>

        <property name="myMap">
            <props>
                <prop key="testC">ccc</prop>
                <prop key="testD">ddd</prop>
            </props>
        </property>

        <property name="myProps">
            <map>
                <entry key="testA" value="aaa"></entry>
                <entry key="testB">
                    <value>BBB</value>
                </entry>
            </map>
        </property>
    </bean>
</beans>
           
spring第二天:spring基于注解的IOC以及IoC的案例
1、spring中ioc的常用注解
2、案例使用xml方式和注解方式實作單表的CRUD操作
	持久層技術選擇:dbutils
3、改造基于注解的ioc案例,使用純注解的方式實作
	spring的一些新注解使用
4、spring和Junit整合
           

2 第二天

2.1 注解IOC
  • IAccountDao.java;
package com.itheima.dao;

/**
 * 賬戶的持久層接口
 */
public interface IAccountDao {
    /**
     * 模拟儲存賬戶
     */
    void saveAccount();
}
           
  • AccountDaoImpl.java;
package com.itheima.dao.impl;

import com.itheima.dao.IAccountDao;
import org.springframework.stereotype.Repository;

/**
 * 賬戶的持久層實作類
 */
@Repository("accountDao1")
public class AccountDaoImpl implements IAccountDao {
    public void saveAccount() {
        System.out.println("儲存了賬戶1111111111111");
    }
}
           
  • AccountDaoImpl2.java;
package com.itheima.dao.impl;

import com.itheima.dao.IAccountDao;
import org.springframework.stereotype.Repository;

/**
 * 賬戶的持久層實作類
 */
@Repository("accountDao2")
public class AccountDaoImpl2 implements IAccountDao {
    public void saveAccount() {
        System.out.println("儲存了賬戶2222222222222");
    }
}
           
  • IAccountService.java;
package com.itheima.service;

/**
 * 賬戶業務層的接口
 */
public interface IAccountService {
    /**
     * 模拟儲存賬戶
     */
    void saveAccount();
}
           
  • AccountServiceImpl.java;
package com.itheima.service.impl;

import com.itheima.dao.IAccountDao;
import com.itheima.service.IAccountService;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;

/**
 * 賬戶的業務層實作類
 * 曾經XML的配置:
 *  <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"
 *        scope=""  init-method="" destroy-method="">
 *      <property name=""  value="" | ref=""></property>
 *  </bean>
 *
 * 用于建立對象的
 *      他們的作用就和在XML配置檔案中編寫一個<bean>标簽實作的功能是一樣的
 *      Component:
 *          作用:用于把目前類對象存入spring容器中
 *          屬性:
 *              value:用于指定bean的id,當我們不寫時,它的預設值是目前類名,且首字母改小寫
 *      Controller:一般用在表現層
 *      Service:一般用在業務層
 *      Repository:一般用在持久層
 *      以上三個注解他們的作用和屬性與Component是一模一樣
 *      他們三個是spring架構為我們提供明确的三層使用的注解,使我們的三層對象更加清晰
 *
 * 用于注入資料的
 *      他們的作用就和在xml配置檔案中的bean标簽中寫一個<property>标簽的作用是一樣的
 *      Autowired:
 *          作用:自動按照類型注入。隻要容器中有唯一的一個bean對象類型和要注入的變量類型比對,就可以注入成功
 *                如果ioc容器中沒有任何bean的類型和要注入的變量類型比對,則報錯
 *                如果Ioc容器中有多個類型比對時:
 *          出現位置:
 *              可以是變量上,也可以是方法上
 *          細節:
 *              在使用注解注入時,set方法就不是必須的了
 *      Qualifier:
 *          作用:在按照類中注入的基礎之上再按照名稱注入,它在給類成員注入時不能單獨使用。但是在給方法參數注入時可以(稍後我們講)
 *          屬性:
 *              value:用于指定注入bean的id
 *      Resource
 *          作用:直接按照bean的id注入,它可以獨立使用
 *          屬性:
 *              name:用于指定bean的id
 *      以上三個注入都隻能注入其他bean類型的資料,而基本類型和String類型無法使用上述注解實作
 *      另外,集合類型的注入隻能通過XML來實作
 *
 *      Value
 *          作用:用于注入基本類型和String類型的資料
 *          屬性:
 *              value:用于指定資料的值,它可以使用spring中SpEL(也就是spring的el表達式)
 *                      SpEL的寫法:${表達式}
 *
 * 用于改變作用範圍的
 *      他們的作用就和在bean标簽中使用scope屬性實作的功能是一樣的
 *      Scope
 *          作用:用于指定bean的作用範圍
 *          屬性:
 *              value:指定範圍的取值,常用取值:singleton prototype
 *
 * 和生命周期相關 了解
 *      他們的作用就和在bean标簽中使用init-method和destroy-methode的作用是一樣的
 *      PreDestroy
 *          作用:用于指定銷毀方法
 *      PostConstruct
 *          作用:用于指定初始化方法
 */
@Service("accountService")
//@Scope("prototype")
public class AccountServiceImpl implements IAccountService {

//    @Autowired
//    @Qualifier("accountDao1")
    @Resource(name = "accountDao2")
    private IAccountDao accountDao = null;

    @PostConstruct
    public void init() {
        System.out.println("初始化方法執行了");
    }

    @PreDestroy
    public void destroy() {
        System.out.println("銷毀方法執行了");
    }

    public void saveAccount() {
        accountDao.saveAccount();
    }
}
           
  • bean.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"
       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">

    <!--告知spring在建立容器時要掃描的包,配置所需要的标簽不是在beans的限制中,而是一個名稱為
    context名稱空間和限制中-->
    <context:component-scan base-package="com.itheima"></context:component-scan>
</beans>
           
2.2 基于XML的IOC案例
  • Account.java;
package com.itheima.domain;

import java.io.Serializable;

/**
 * 賬戶的實體類
 */
public class Account implements Serializable {
    private Integer id;
    private String name;
    private Float money;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Float getMoney() {
        return money;
    }

    public void setMoney(Float money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + ''' +
                ", money=" + money +
                '}';
    }
}
           
  • IAccountDao.java;
package com.itheima.dao;

import com.itheima.domain.Account;
import java.util.List;

/**
 * 賬戶的持久層接口
 */
public interface IAccountDao {
    List<Account> findAllAccount();
    
    Account findAccountById(Integer accountId);

    void saveAccount(Account account);

    void updateAccount(Account account);

    void deleteAccount(Integer acccountId);
}
           
  • AccountDaoImpl.java;
package com.itheima.dao.impl;

import com.itheima.dao.IAccountDao;
import com.itheima.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.util.List;

/**
 * 賬戶的持久層實作類
 */
public class AccountDaoImpl implements IAccountDao {
    private QueryRunner runner;

    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }

    @Override
    public List<Account> findAllAccount() {
        try{
            return runner.query("select * from account", new BeanListHandler<Account>(Account.class));
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Account findAccountById(Integer accountId) {
        try{
            return runner.query("select * from account where id = ? ", new BeanHandler<Account>(Account.class),accountId);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void saveAccount(Account account) {
        try{
            runner.update("insert into account(name,money)values(?,?)", account.getName(), account.getMoney());
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateAccount(Account account) {
        try{
            runner.update("update account set name=?,money=? where id=?", account.getName(), account.getMoney(), account.getId());
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteAccount(Integer accountId) {
        try{
            runner.update("delete from account where id=?", accountId);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
           
  • IAccountService.java;
package com.itheima.service;

import com.itheima.domain.Account;
import java.util.List;

/**
 * 賬戶的業務層接口
 */
public interface IAccountService {
    List<Account> findAllAccount();

    Account findAccountById(Integer accountId);

    void saveAccount(Account account);

    void updateAccount(Account account);

    void deleteAccount(Integer acccountId);
}
           
  • AccountServiceImpl.java;
package com.itheima.service.impl;

import com.itheima.dao.IAccountDao;
import com.itheima.domain.Account;
import com.itheima.service.IAccountService;
import java.util.List;

/**
 * 賬戶的業務層實作類
 */
public class AccountServiceImpl implements IAccountService{
    private IAccountDao accountDao;

    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }

    @Override
    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }

    @Override
    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
    }

    @Override
    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }

    @Override
    public void deleteAccount(Integer acccountId) {
        accountDao.deleteAccount(acccountId);
    }
}
           
  • bean.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- 配置Service -->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
        <!-- 注入dao -->
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <!--配置Dao對象-->
    <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
        <!-- 注入QueryRunner -->
        <property name="runner" ref="runner"></property>
    </bean>

    <!--配置QueryRunner-->
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
        <!--注入資料源-->
        <constructor-arg name="ds" ref="dataSource"></constructor-arg>
    </bean>

    <!-- 配置資料源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--連接配接資料庫的必備資訊-->
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/eesy"></property>
        <property name="user" value="root"></property>
        <property name="password" value="1234"></property>
    </bean>
</beans>
           
  • AccountServiceTest.java;
package com.itheima.test;

import com.itheima.domain.Account;
import com.itheima.service.IAccountService;
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 java.util.List;

/**
 * 使用Junit單元測試:測試我們的配置
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {
    @Autowired
    private IAccountService as;

    @Test
    public void testFindAll() {
        //3.執行方法
        List<Account> accounts = as.findAllAccount();
        for(Account account : accounts) {
            System.out.println(account);
        }
    }

    @Test
    public void testFindOne() {
        //3.執行方法
        Account account = as.findAccountById(1);
        System.out.println(account);
    }

    @Test
    public void testSave() {
        Account account = new Account();
        account.setName("test");
        account.setMoney(12345f);
        //3.執行方法
        as.saveAccount(account);
    }

    @Test
    public void testUpdate() {
        //3.執行方法
        Account account = as.findAccountById(4);
        account.setMoney(23456f);
        as.updateAccount(account);
    }

    @Test
    public void testDelete() {
        //3.執行方法
        as.deleteAccount(4);
    }
}
           
2.3 基于注解的IOC
  • Account.java;
package com.itheima.domain;

import java.io.Serializable;

/**
 * 賬戶的實體類
 */
public class Account implements Serializable {
    private Integer id;
    private String name;
    private Float money;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Float getMoney() {
        return money;
    }

    public void setMoney(Float money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + ''' +
                ", money=" + money +
                '}';
    }
}
           
  • IAccountDao.java;
package com.itheima.dao;

import com.itheima.domain.Account;
import java.util.List;

/**
 * 賬戶的持久層接口
 */
public interface IAccountDao {
    List<Account> findAllAccount();

    Account findAccountById(Integer accountId);

    void saveAccount(Account account);

    void updateAccount(Account account);

    void deleteAccount(Integer acccountId);
}
           
  • AccountDaoImpl.java;
package com.itheima.dao.impl;

import com.itheima.dao.IAccountDao;
import com.itheima.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;

/**
 * 賬戶的持久層實作類
 */
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
    @Autowired
    private QueryRunner runner;

    @Override
    public List<Account> findAllAccount() {
        try{
            return runner.query("select * from account", new BeanListHandler<Account>(Account.class));
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Account findAccountById(Integer accountId) {
        try{
            return runner.query("select * from account where id = ? ", new BeanHandler<Account>(Account.class), accountId);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void saveAccount(Account account) {
        try{
            runner.update("insert into account(name,money)values(?,?)", account.getName(), account.getMoney());
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateAccount(Account account) {
        try{
            runner.update("update account set name=?,money=? where id=?", account.getName(), account.getMoney(), account.getId());
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteAccount(Integer accountId) {
        try{
            runner.update("delete from account where id=?", accountId);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
           
  • IAccountService.java;
package com.itheima.service;

import com.itheima.domain.Account;
import java.util.List;

/**
 * 賬戶的業務層接口
 */
public interface IAccountService {
    List<Account> findAllAccount();

    Account findAccountById(Integer accountId);

    void saveAccount(Account account);

    void updateAccount(Account account);

    void deleteAccount(Integer acccountId);
}
           
  • AccountServiceImpl.java;
package com.itheima.service.impl;

import com.itheima.dao.IAccountDao;
import com.itheima.domain.Account;
import com.itheima.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

/**
 * 賬戶的業務層實作類
 */
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
    @Autowired
    private IAccountDao accountDao;

    @Override
    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }

    @Override
    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }

    @Override
    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
    }

    @Override
    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }

    @Override
    public void deleteAccount(Integer acccountId) {
        accountDao.deleteAccount(acccountId);
    }
}
           
  • bean.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"
       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">

    <!-- 告知spring在建立容器時要掃描的包 -->
    <context:component-scan base-package="com.itheima"></context:component-scan>
    <!--配置QueryRunner-->
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
        <!--注入資料源-->
        <constructor-arg name="ds" ref="dataSource"></constructor-arg>
    </bean>

    <!-- 配置資料源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--連接配接資料庫的必備資訊-->
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/eesy"></property>
        <property name="user" value="root"></property>
        <property name="password" value="1234"></property>
    </bean>
</beans>
           
  • AccountServiceTest.java;
package com.itheima.test;

import com.itheima.domain.Account;
import com.itheima.service.IAccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;

/**
 * 使用Junit單元測試:測試我們的配置
 */
public class AccountServiceTest {
    @Test
    public void testFindAll() {
        //1.擷取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到業務層對象
        IAccountService as = ac.getBean("accountService", IAccountService.class);
        //3.執行方法
        List<Account> accounts = as.findAllAccount();
        for(Account account : accounts){
            System.out.println(account);
        }
    }

    @Test
    public void testFindOne() {
        //1.擷取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到業務層對象
        IAccountService as = ac.getBean("accountService", IAccountService.class);
        //3.執行方法
        Account account = as.findAccountById(1);
        System.out.println(account);
    }

    @Test
    public void testSave() {
        Account account = new Account();
        account.setName("test");
        account.setMoney(12345f);
        //1.擷取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到業務層對象
        IAccountService as = ac.getBean("accountService", IAccountService.class);
        //3.執行方法
        as.saveAccount(account);
    }

    @Test
    public void testUpdate() {
        //1.擷取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到業務層對象
        IAccountService as = ac.getBean("accountService", IAccountService.class);
        //3.執行方法
        Account account = as.findAccountById(4);
        account.setMoney(23456f);
        as.updateAccount(account);
    }

    @Test
    public void testDelete() {
        //1.擷取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到業務層對象
        IAccountService as = ac.getBean("accountService", IAccountService.class);
        //3.執行方法
        as.deleteAccount(4);
    }
}
           

參考

Spring教程IDEA版-4天-2018黑馬SSM-02_哔哩哔哩 (゜-゜)つロ 幹杯~-bilibili​www.bilibili.com