Spring基于纯注解的配置

本文详细介绍了在Spring框架中如何实现账户服务,包括配置数据源、定义DAO接口及其实现,以及通过单元测试验证服务功能。从配置文件读取数据库参数,到使用QueryRunner执行SQL,再到业务层接口与实现,全面展示了账户增删改查的全过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.jdbcConfig.properties

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/spring
jdbc.username = root
jdbc.password = 123

2.com.config.jdbcConfig

package config;
import javax.sql.DataSource;

public class jdbcConfig {
    @Value("${jdbc.driver}")
    private String driver;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")
    private String password;

    //用于创建一个QueryRunner对象
    @Bean(name = "runner")
    @Scope(value = "prototype")
    public QueryRunner createQueryRunner(DataSource dataSource){
        return new QueryRunner(dataSource);
    }

    //创建数据源对象
    @Bean(name = "dataSource")
    public DataSource createDataSource(){
        try{
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass(driver);
            ds.setJdbcUrl(url);
            ds.setUser(username);
            ds.setPassword(password);
            return ds;
        }catch (Exception e){
            throw  new RuntimeException(e);
        }
    }
}

3.com.config.SpringConfiguration

package config;
@ComponentScan(basePackages = {"com"})
@Import(jdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {

}

4.com.service.AccountServiceImpl

package com.dao.Impl;
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao{

    @Autowired
    private QueryRunner runner;

    public List<Account> findAllAccount() {
        try {
            String sql = "select * from account";
            return runner.query(sql,new BeanListHandler<Account>(Account.class));
        } catch (SQLException e) {
            throw new RuntimeException("运行出错");
        }
    }

    public Account findAccountById(Integer id) {
        try {
            String sql = "select * from account where id = ?";
            return runner.query(sql,new BeanHandler<Account>(Account.class),id);
        } catch (SQLException e) {
            throw new RuntimeException("运行出错");
        }
    }

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

    public void updateAccount(Account account) {
        try {
            String sql = "update account set name = ?,money = ? where id=?";
            runner.update(sql,account.getName(),account.getMoney(),account.getId());
        } catch (SQLException e) {
            throw new RuntimeException("运行出错");
        }
    }

    public void deleteAccount(Integer id) {
        try {
            String sql = "delete from account where id = ?";
            runner.update(sql,id);
        } catch (SQLException e) {
            throw new RuntimeException("运行出错");
        }
    }
}

5.com.service.IAccountService

package com.service;
/*
    账户的业务层接口
 */
public interface IAccountService {

    //查询所有
    List<Account> findAllAccount();

    //查询一个
    Account findAccountById(Integer id);

    //保存账户
    void saveAccount(Account account);

    //更新
    void updateAccount(Account account);

    //删除
    void deleteAccount(Integer id);
}

6.com.domain.Account

package com.domain;

/*
    账户的实体类
 */
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 +
                '}';
    }
}

7.com.dao.Impl.AccountDaoImpl

package com.dao.Impl;

@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao{

    @Autowired
    private QueryRunner runner;

    public List<Account> findAllAccount() {
        try {
            String sql = "select * from account";
            return runner.query(sql,new BeanListHandler<Account>(Account.class));
        } catch (SQLException e) {
            throw new RuntimeException("运行出错");
        }
    }

    public Account findAccountById(Integer id) {
        try {
            String sql = "select * from account where id = ?";
            return runner.query(sql,new BeanHandler<Account>(Account.class),id);
        } catch (SQLException e) {
            throw new RuntimeException("运行出错");
        }
    }

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

    public void updateAccount(Account account) {
        try {
            String sql = "update account set name = ?,money = ? where id=?";
            runner.update(sql,account.getName(),account.getMoney(),account.getId());
        } catch (SQLException e) {
            throw new RuntimeException("运行出错");
        }
    }

    public void deleteAccount(Integer id) {
        try {
            String sql = "delete from account where id = ?";
            runner.update(sql,id);
        } catch (SQLException e) {
            throw new RuntimeException("运行出错");
        }
    }
}

8.com.dao.IAccountDao

package com.dao;
public interface IAccountDao {
    //查询所有
    List<Account> findAllAccount();

    //查询一个
    Account findAccountById(Integer id);

    //保存账户
    void saveAccount(Account account);

    //更新
    void updateAccount(Account account);

    //删除
    void deleteAccount(Integer id);
}

9.com.test.AccountServiceTest

package com.test;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {

    @Autowired
    private IAccountService accountService;


    @Test
    public void testFindAll(){
        List<Account> accounts = accountService.findAllAccount();
        for(Account account : accounts){
            System.out.println(account);
        }
    }
    @Test
    public void testFindOne(){
        Account account = accountService.findAccountById(1);
        System.out.println(account);
    }
    @Test
    public void testSave(){
        Account account = new Account();
        account.setName("ddd");
        account.setMoney(4000.0f);
        accountService.saveAccount(account);
    }
    @Test
    public void testUpdate(){

        Account account = new Account();
        account.setId(4);
        account.setName("eee");
        account.setMoney(4000.0f);
        accountService.updateAccount(account);
    }
    @Test
    public void testDelete(){
        accountService.deleteAccount(4);
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值