Spring5(5)- 基於註解的小案例

1 Dao

在這裏插入圖片描述

2 Service

在這裏插入圖片描述

3 bean.xml

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

<!--導入 spring 約束-->
<!--基於註解的IOC配置需要導入 context 名稱空間-->
<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.tzb"></context:component-scan>

    <!--此時是一個多例對象-->
    <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/spring5?userSSL=false"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
    </bean>

</beans>

4 單元測試

   @Test
    public void testFindAll(){
        // 獲取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");

        IAccountService as = ac.getBean("accountService", AccountServiceImpl.class);

        List<Account> accounts = as.findAllAccount();
        System.out.println(accounts);
    }

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章