06-基于 XML 和注解 的 IOC 案例

Posted zuiren

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了06-基于 XML 和注解 的 IOC 案例相关的知识,希望对你有一定的参考价值。

新建一个 maven 工程

一、pom.xml 配置

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>spring05</groupId>
    <artifactId>spring05</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-dbutils/commons-dbutils -->
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.7</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.4</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>


    </dependencies>

</project>

二、创建接口、数据库表与实体类

技术图片

1.数据库表

create table account02(
    id int primary key auto_increment,
    name varchar(40),
    money float
);

insert into account02(name,money) values ('aaa',10),('bbb',100),('ccc',1000);

2.实体类

创建 domain 文件夹

创建 Account 类生成get,set方法还有 tostring 方法

package com.domain;

public class Account 
    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 +
                '';
    

3.数据访问层

Ⅰ 接口类

package com.dao;

import com.domain.Account;

import java.util.List;

/**
 * 描述:
 〈账户的持久层接口〉
 * @author zuiren
 * @create 2019/8/27
 * @since 1.0.0
 */
public interface IAccountDao 
    /**
     * 查询所有
     * @return
     */
    List<Account> findAllAccount();

    /**
     * 查询一个
     * @param accountId
     * @return
     */
    Account findAccountById(Integer accountId);

    /**
     * 保存
     * @param account
     */
    void saveAccount(Account account);

    /**
     * 更新
     * @param account
     */
    void updateAccount(Account account);

    /**
     * 修改
     * @param accountId
     */
    void deleteAccount(Integer accountId);

Ⅱ 实现类

package com.dao.Impl;

import com.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * 描述:
 * 〈账户的持久层实现类〉
 *
 * @author zuiren
 * @create 2019/8/27
 * @since 1.0.0
 */
public class IAccountDaoImpl implements com.dao.IAccountDao 

    private QueryRunner runner;

    public IAccountDaoImpl(QueryRunner runner) 
        this.runner = runner;
    

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

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

    public void saveAccount(Account account) 
        try 
            runner.update("insert into account02(name,money) values(?,?)",account.getName(),account.getMoney());
        catch (SQLException e)
            e.printStackTrace();
        
    

    public void updateAccount(Account account) 
        try 
            runner.update("update account02 set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
        catch (SQLException e)
            e.printStackTrace();
        
    

    public void deleteAccount(Integer accountId) 
        try 
            runner.update("delete from account02 where id=?",accountId);
        catch (SQLException e)
            e.printStackTrace();
        
    

4.业务逻辑层

Ⅰ 接口类

package com.service;

import com.domain.Account;

import java.util.List;

/**
 * 描述:
 〈账户的业务层接口〉
 * @author zuiren
 * @create 2019/8/27
 * @since 1.0.0
 */
public interface IAccountService 
    /**
     * 查询所有
     * @return
     */
    List<Account> findAllAccount();

    /**
     * 查询一个
     * @param accountId
     * @return
     */
    Account findAccountById(Integer accountId);

    /**
     * 保存
     * @param account
     */
    void saveAccount(Account account);

    /**
     * 更新
     * @param account
     */
    void updateAccount(Account account);

    /**
     * 修改
     * @param accountId
     */
    void deleteAccount(Integer accountId);

Ⅱ 实现类

package com.service.Impl;

import com.dao.IAccountDao;
import com.domain.Account;
import com.service.IAccountService;

import java.util.List;

/**
 * 描述:
 * 〈账户的业务层实现类〉
 *
 * @author zuiren
 * @create 2019/8/27
 * @since 1.0.0
 */
public class AccountServiceImpl implements IAccountService 

    private IAccountDao accountDao;

    public AccountServiceImpl(IAccountDao accountDao) 
        this.accountDao = accountDao;
    

    public List<Account> findAllAccount() 
        return accountDao.findAllAccount();
    

    public Account findAccountById(Integer accountId) 
        return accountDao.findAccountById(accountId);
    

    public void saveAccount(Account account) 
        accountDao.saveAccount(account);
    

    public void updateAccount(Account account) 
        accountDao.updateAccount(account);
    

    public void deleteAccount(Integer accountId) 
        accountDao.deleteAccount(accountId);
    

三、bean.xml

在 resources 文件夹下创建 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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--配置 Service-->
    <bean id="accountService" class="com.service.Impl.AccountServiceImpl">
        <constructor-arg ref="accountDao"/>
        <!--注入 dao-->
    </bean>
    
    <!--配置 Dao-->
    <bean id="accountDao" class="com.dao.Impl.IAccountDaoImpl">
        <!--注入QueryRunner-->
        <constructor-arg ref="runner"/>
    </bean>
    
    <!--配置QueryRunner   默认为单例对象-->
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
        <!--QueryRunner 可以带参创建,也可以无参构造,有区别,你希望每条语句独立一个事务,还是所有的语句在同一个事务中
            由于此处是单表,一条语句的 crud 的操作,所以此时可以选择传入数据源
        -->

        <!--注入数据源-->
        <constructor-arg name="ds" ref="dataSource"/>
    </bean>

    <!--配置数据源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--连接数据库的必备信息-->
        <property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test?useSSL=false&amp;serverTimezone=GMT"/>
        <property name="user" value="root"/>
        <property name="password" value="root"/>
    </bean>
</beans>

四、Test

在 test 下创建 AccountServiceTest 类

package com.test;

import com.domain.Account;
import com.service.IAccountService;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

/**
 * 描述:
 * 〈使用 junit 单元测试:测试我们配置〉
 *
 * @author zuiren
 * @create 2019/8/28
 * @since 1.0.0
 */
public class AccountServiceTest 
    //1.获取容器
    ApplicationContext ac=null;
    //2.得到业务层对象
    IAccountService as=null;

    @Before
    public void init()
        //1.获取容器
        ac=new ClassPathXmlApplicationContext("bean.xml");
        //2.得到业务层对象
        as=ac.getBean("accountService",IAccountService.class);
    

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

    @Test
    public void testFindAccountById()
        //3.执行方法
        Account account=as.findAccountById(1);
        System.out.println(account);
    

    @Test
    public void testSaveAccount()
        //3.执行方法
        Account account=new Account();
        account.setName("卡兹克");
        account.setMoney(300);

        as.saveAccount(account);
    

    @Test
    public void testUpdateAccount()

    

    @Test
    public void testDeleteAccount()

    

[TOC]

五、基于注解

1. 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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <!--告知 spring 在创建容器时要扫描的白-->
    <context:component-scan base-package="com"/>

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

    <!--配置数据源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--连接数据库的必备信息-->
        <property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test?useSSL=false&amp;serverTimezone=GMT"/>
        <property name="user" value="root"/>
        <property name="password" value="root"/>
    </bean>

</beans>

2. dao

package com.dao.Impl;

import com.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.sql.SQLException;
import java.util.List;

/**
 * 描述:
 * 〈账户的持久层实现类〉
 *
 * @author zuiren
 * @create 2019/8/27
 * @since 1.0.0
 */
@Repository(value = "accountDao")
public class IAccountDaoImpl implements com.dao.IAccountDao 

    @Autowired
    private QueryRunner runner;

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

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

    public void saveAccount(Account account) 
        try 
            runner.update("insert into account02(name,money) values(?,?)",account.getName(),account.getMoney());
        catch (SQLException e)
            e.printStackTrace();
        
    

    public void updateAccount(Account account) 
        try 
            runner.update("update account02 set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
        catch (SQLException e)
            e.printStackTrace();
        
    

    public void deleteAccount(Integer accountId) 
        try 
            runner.update("delete from account02 where id=?",accountId);
        catch (SQLException e)
            e.printStackTrace();
        
    

3. service

package com.service.Impl;

import com.dao.IAccountDao;
import com.domain.Account;
import com.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 描述:
 * 〈账户的业务层实现类〉
 *
 * @author zuiren
 * @create 2019/8/27
 * @since 1.0.0
 */
@Service(value = "accountService")
public class AccountServiceImpl implements IAccountService 

    @Autowired
    private IAccountDao accountDao;

    public List<Account> findAllAccount() 
        return accountDao.findAllAccount();
    

    public Account findAccountById(Integer accountId) 
        return accountDao.findAccountById(accountId);
    

    public void saveAccount(Account account) 
        accountDao.saveAccount(account);
    

    public void updateAccount(Account account) 
        accountDao.updateAccount(account);
    

    public void deleteAccount(Integer accountId) 
        accountDao.deleteAccount(accountId);
    

以上是关于06-基于 XML 和注解 的 IOC 案例的主要内容,如果未能解决你的问题,请参考以下文章

Spring 从入门到精通系列 07——基于XML与注解方式的IOC案例编写

spring

spring

spring

spring基于注解的IOC

Spring学习的第二天