Spring基于 XML 的IoC配置(实现账户的CURD)

一、Spring基于纯 XML 的IoC配置

Spring基于 XML 的IoC配置(实现账户的CURD)_第1张图片
第一步:新建实体类 Account.java 来映射上面的数据库表

package cn.lemon.domain;

public class Account {
    private Integer id;
    private String name;
    private Double 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 Double getMoney() {
        return money;
    }

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

第二步:新建数据库访问层(dao)
IAccountDao.java接口

package cn.lemon.dao;

import cn.lemon.domain.Account;

import java.util.List;

public interface IAccountDao {
    void addAccount(Account account);

    void deleteAccount(Integer accountId);

    void updateAccount(Account account);

    Account findOne(Integer accountId);

    List<Account> findAll();
}

接口的实现类 AccountDaoImpl.java

package cn.lemon.dao.impl;

import cn.lemon.dao.IAccountDao;
import cn.lemon.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class AccountDaoImpl implements IAccountDao {
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

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

    @Override
    public void deleteAccount(Integer accountId) {
        try{
            jdbcTemplate.update("delete from account where id = ?",accountId);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

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

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

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

第三步:新建业务逻辑层(service)
IAccountService.java接口

package cn.lemon.service;

import cn.lemon.domain.Account;

import java.util.List;

public interface IAccountService {
    void addAccount(Account account);

    void deleteAccount(Integer accountId);

    void updateAccount(Account account);

    Account findOne(Integer accountId);

    List<Account> findAll();
}

接口的实现类 AccountServiceImpl.java

package cn.lemon.service.impl;

import cn.lemon.dao.IAccountDao;
import cn.lemon.domain.Account;
import cn.lemon.service.IAccountService;

import java.util.List;

public class AccountServiceImpl implements IAccountService {
    private IAccountDao iAccountDao;

    public void setiAccountDao(IAccountDao iAccountDao) {
        this.iAccountDao = iAccountDao;
    }

    @Override
    public void addAccount(Account account) {
        iAccountDao.addAccount(account);
    }

    @Override
    public void deleteAccount(Integer accountId) {
        iAccountDao.deleteAccount(accountId);
    }

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

    @Override
    public Account findOne(Integer accountId) {
        return iAccountDao.findOne(accountId);
    }

    @Override
    public List<Account> findAll() {
        return iAccountDao.findAll();
    }
}

第四步:新建 xml Spring配置文件 applicationContext.xml


<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">
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver">property>
    <property name="url" value="jdbc:mysql:///db_account">property>
    <property name="username" value="root">property>
    <property name="password" value="lemon">property>
bean>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource">property>
    bean>
    <bean id="accountDao" class="cn.lemon.dao.impl.AccountDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate">property>
    bean>
    <bean id="accountService" class="cn.lemon.service.impl.AccountServiceImpl">
        <property name="iAccountDao" ref="accountDao">property>
    bean>
beans>

第五步:新建测试类 AccountServiceImplTest.java ,实现数据库的增删改查

package cn.lemon.service.impl;

import cn.lemon.domain.Account;
import cn.lemon.service.IAccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class AccountServiceImplTest {
    private IAccountService iAccountService;

    public AccountServiceImplTest() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        iAccountService = (IAccountService) applicationContext.getBean("accountService");
    }

    @Test
    public void addAccount() {
        Account account = new Account();
        account.setName("马东敏");
        account.setMoney(10d);
        iAccountService.addAccount(account);
    }

    @Test
    public void deleteAccount() {
        iAccountService.deleteAccount(14);
    }

    @Test
    public void updateAccount() {
        Account account = iAccountService.findOne(17);
        account.setName("张英");
        iAccountService.updateAccount(account);
    }

    @Test
    public void findOne() {
        Account account = iAccountService.findOne(1);
        System.out.println("ID:" + account.getId() + "\tName:" + account.getName() + "\tMoney:" + account.getMoney());
    }

    @Test
    public void findAll() {
        List<Account> accountList = iAccountService.findAll();
        for (Account account : accountList) {
            System.out.println("ID:" + account.getId() + "\tName:" + account.getName() + "\tMoney:" + account.getMoney());
        }
    }
}

二、Spring基于 XML和注解的IoC配置


通过 @Component 和 @Autowired 修改上面的代码
Spring基于 XML 的IoC配置(实现账户的CURD)_第2张图片
注意:使用 @Autowired 时,set 方法可以省略

第一步:修改数据访问层的实现类 AccountDaoImpl.java

package cn.lemon.dao.impl;

import cn.lemon.dao.IAccountDao;
import cn.lemon.domain.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Component:在spring 中产生对象,相当于 
 * 默认的id为:accountDaoImpl(类名的首字母小写),可以使用默认的
 * @Repository 专门用于 dao 层
 */
@Component
//@Repository
public class AccountDaoImpl implements IAccountDao {
    /**
     * @Autowired :依赖注入的注解
     * 默认找Spring容器中,跟属性类型相同的对象注入
     * 可以不写set 方法
     * 如果有多个类型相同的对象,或者没有响应类型的对象,会报错
     * 使用 @Qualifier 指定 id 注入
     */
    @Autowired
    private JdbcTemplate jdbcTemplate;

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

    @Override
    public void deleteAccount(Integer accountId) {
        try {
            jdbcTemplate.update("delete from account where id = ?", accountId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

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

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

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

第二步:修改业务逻辑层的实现类 AccountServiceImpl.java

package cn.lemon.service.impl;

import cn.lemon.dao.IAccountDao;
import cn.lemon.domain.Account;
import cn.lemon.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

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

/**
 * Component:在spring 中产生对象,相当于 
 * 默认的id为:accountServiceImpl(类名的首字母小写),可以使用默认的
 *
 * @Service 专门用于 Service 层
 */
@Component("accountServiceImpl")
//@Service
public class AccountServiceImpl implements IAccountService {
    /**
     * @Autowired :依赖注入的注解
     * 默认找Spring容器中,跟属性类型相同的对象注入
     * 可以不写set 方法
     * 如果有多个类型相同的对象,或者没有响应类型的对象,会报错
     * 使用 @Qualifier 指定 id 注入,或者在 xml 配置文件中使用 primary = true
     * @Resource 依赖注入的注解
     */
    //@Autowired
    //@Qualifier("accountDaoImpl")
    @Resource(name = "accountDaoImpl")
    private IAccountDao iAccountDao;

    @Value("这是下面 name 的值")
    private String name;

    @Override
    public void addAccount(Account account) {
        iAccountDao.addAccount(account);
    }

    @Override
    public void deleteAccount(Integer accountId) {
        iAccountDao.deleteAccount(accountId);
    }

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

    @Override
    public Account findOne(Integer accountId) {
        return iAccountDao.findOne(accountId);
    }

    @Override
    public List<Account> findAll() {
        System.out.println(name);
        return iAccountDao.findAll();
    }
}

第三步:修改测试类 AccountServiceImplTest.java

package cn.lemon.service.impl;

import cn.lemon.domain.Account;
import cn.lemon.service.IAccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class AccountServiceImplTest {
    private IAccountService iAccountService;

    public AccountServiceImplTest() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        iAccountService = (IAccountService) applicationContext.getBean("accountServiceImpl");
    }

    @Test
    public void addAccount() {
        Account account = new Account();
        account.setName("马东敏");
        account.setMoney(10d);
        iAccountService.addAccount(account);
    }

    @Test
    public void deleteAccount() {
        iAccountService.deleteAccount(14);
    }

    @Test
    public void updateAccount() {
        Account account = iAccountService.findOne(17);
        account.setName("张英");
        iAccountService.updateAccount(account);
    }

    @Test
    public void findOne() {
        Account account = iAccountService.findOne(1);
        System.out.println("ID:" + account.getId() + "\tName:" + account.getName() + "\tMoney:" + account.getMoney());
    }

    @Test
    public void findAll() {
        List<Account> accountList = iAccountService.findAll();
        for (Account account : accountList) {
            System.out.println("ID:" + account.getId() + "\tName:" + account.getName() + "\tMoney:" + account.getMoney());
        }
    }
}

三、Spring基于纯注解的 IoC 配置

请点击 Spring 基于注解的AOP配置

你可能感兴趣的:(框架Spring)