基于注解的IOC的案例

基于注解的IOC的案例
1.打开IDEA工具如图所示的界面,点击Create New Project。在这里插入图片描述
2.选择Maven工程和JDK的版本,如图所示:并点击Next。在这里插入图片描述
3.填写项目名称和保存的地址,点击Finish。如图所示:
在这里插入图片描述
4.导入相应的依赖jar包的代码如下:

<?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>com.txw</groupId>
    <artifactId>spring_03account_annoioc</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!--打包的方式 -->
    <packaging>jar</packaging>
    <dependencies>
    <!--导入spring-context的依赖jar包坐标-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.2.8.RELEASE</version>
    </dependency>
    <!--导入lombok的依赖jar包坐标-->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.12</version>
    </dependency>
    <!--导入mysql的依赖jar包坐标-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>6.0.6</version>
    </dependency>
    <!--导入commons-dbutils的依赖jar包坐标-->
    <dependency>
        <groupId>commons-dbutils</groupId>
        <artifactId>commons-dbutils</artifactId>
        <version>1.7</version>
    </dependency>
    <!--导入spring-test的依赖jar包坐标-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>5.2.8.RELEASE</version>
    </dependency>
    <!--导入c3p0的依赖jar包坐标-->
    <dependency>
        <groupId>c3p0</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.1.2</version>
    </dependency>
    <!--导入junit的依赖jar包坐标-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13</version>
    </dependency>
    </dependencies>
</project>

5.编写账户实体类的代码如下:

package com.txw.domain;

import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
/**
 * 账户的实体类
 * @author:Adair
 * @QQ:1578533828
 */
@Data     // 自动生成set和get方法
@ToString // 重写toString方法
@SuppressWarnings("all")      // 注解警告信息
public class Account implements Serializable {
    private Integer id;      // 账户的id
    private String name;     // 账户的名称
    private Float money;     // 账户的金额
}

6.编写账户的业务层接口代码如下:

package com.txw.service;

import com.txw.domain.Account;
import java.util.List;
/**
 *账户的业务层接口
 * @author:Adair
 * @QQ:1578533828
 */
@SuppressWarnings("all")      // 注解警告信息
public interface AccountService {
    /**
     * 查询所有
     * @return
     */
    List<Account> findAllAccount();
    /**
     * 根据id查询一个
     * @return
     */
    Account findAccountById(Integer accountId);
    /**
     * 保存账户
     * @param account
     */
    void saveAccount(Account account);
    /**
     * 更新账户
     * @param account
     */
    void updateAccount(Account account);
    /**
     * 根据id删除
     * @param acccountId
     */
    void deleteAccount(Integer accountId);
}

7.编写账户的业务层实现类代码如下:

package com.txw.service.impl;

import com.txw.dao.AccountDao;
import com.txw.domain.Account;
import com.txw.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
 * 账户的业务层实现类
 * @author:Adair
 * @QQ:1578533828
 */
@Service("accountService")
@SuppressWarnings("all")      // 注解警告信息
public class AccountServiceImpl implements AccountService {
    // 声明AccountDao业务对象
    @Autowired
    private AccountDao accountDao;
    /**
     * 查询所有
     * @return
     */
    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }
    /**
     * 根据id查询一个
     * @return
     */
    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }
    /**
     * 保存账户
     * @param account
     */
    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
    }
    /**
     * 修改账户
     * @param account
     */
    public void updateAccount(Account account) {
    accountDao.updateAccount(account);
    }
    /**
     * 根据id删除
     * @param acccountId
     */
    public void deleteAccount(Integer accountId) {
        accountDao.deleteAccount(accountId);
    }
}

8.编写账户的持久层接口代码如下:

package com.txw.dao;

import com.txw.domain.Account;
import java.util.List;
/**
 * 账户的持久层接口
 * @author:Adair
 * @QQ:1578533828
 */
@SuppressWarnings("all")      // 注解警告信息
public interface AccountDao {
    /**
     * 查询所有
     * @return
     */
    List<Account> findAllAccount();
    /**
     * 根据id查询一个
     * @return
     */
    Account findAccountById(Integer accountId);
    /**
     * 保存账户
     * @param account
     */
    void saveAccount(Account account);
    /**
     * 更新账户
     * @param account
     */
    void updateAccount(Account account);
    /**
     * 根据id删除
     * @param acccountId
     */
    void deleteAccount(Integer accountId);
}

9.编写账户的持久层实现类代码如下:

package com.txw.dao.impl;

import com.txw.dao.AccountDao;
import com.txw.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;
/**
 * 账户的持久层实现类
 * @author:Adair
 * @QQ:1578533828
 */
@Repository("accountDao")
@SuppressWarnings("all")      // 注解警告信息
public class AccountDaoImpl implements AccountDao {
    // 声明QueryRunner业务对象
    @Autowired
    private QueryRunner runner;
    /**
     * 查询所有
     * @return
     */
    public List<Account> findAllAccount() {
        try{
            return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 根据id查询一个
     * @return
     */
    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);
        }
    }
    /**
     * 保存账户
     * @param account
     */
    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);
        }
    }
    /**
     * 修改账户
     * @param account
     */
    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);
        }
    }
    /**
     * 根据id删除
     * @param accountId
     */
    public void deleteAccount(Integer accountId) {
        try{
            runner.update("delete from account where id=?",accountId);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

10.在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"
       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.txw"></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/spring?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=UTC&amp;useSSL=false"/>
        <property name="user" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>
</beans>

11.编写测试的代码如下:

package com.txw.test;

import com.txw.domain.Account;
import com.txw.service.AccountService;
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单元测试:测试我们的配置
 * @author:Adair
 * @QQ:1578533828
 */
@SuppressWarnings("all")      // 注解警告信息
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {
    // 声明AccountService业务对象
    @Autowired
    private AccountService as;
    /**
     * 测试查询所有
     */
    @Test
    public void testFindAll() {
        // 3.执行方法
        List<Account> accounts = as.findAllAccount();
        for(Account account : accounts){
            System.out.println(account);
        }
    }
    /**
     * 测试根据id查询一个
     */
    @Test
    public void testFindOne() {
        //3.执行方法
        Account account = as.findAccountById(1);
        System.out.println(account);
    }
    /**
     * 测试保存账户
     */
    @Test
    public void testSave() {
        Account account = new Account();
        account.setName("Adair");
        account.setMoney(12345f);
        //3.执行方法
        as.saveAccount(account);

    }
    /**
     * 测试修改账户
     */
    @Test
    public void testUpdate() {
        //3.执行方法
        Account account = as.findAccountById(4);
        account.setMoney(23456f);
        as.updateAccount(account);
    }
    /**
     * 测试根据id删除
     */
    @Test
    public void testDelete() {
        //3.执行方法
        as.deleteAccount(4);
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学无止路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值