六、Spring基于纯注解的开发和基于注解加xml配置你怎么选

其实在没有熟悉spring的一些人身上总会觉得spring用纯注解的话会很简单,这也是我最开始的想法,现在我们用下面的代码来看看到底是怎么样的!

我们首先把依赖导入

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.6.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.6.RELEASE</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.7</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>

        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

然后我们来写一个Account实体类

package com.lp.domain;

import java.io.Serializable;

/**
 * @Date 2020/5/27 16:44
 * @Author luopeng
 */
public class Account implements Serializable {
    private Integer id;
    private String name;
    private Float money;

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + 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;
    }
}

该下一步了,把service和dao这些接口先创建好吧
service层接口和到层是一样的,这里只展示一个就够了

package com.lp.dao;

import com.lp.domain.Account;

import java.util.List;

/**
 * 持久层接口
 *
 * @Date 2020/5/27 16:50
 * @Author luopeng
 */
public interface AccountDao {
    /**
     * 查询所有
     *
     * @return
     */
    List<Account> findAllAccount();

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    Account findById(Integer id);

    /**
     * 保存账户
     *
     * @param account
     */
    void save(Account account);

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

    /**
     * 通过id删除账户
     *
     * @param id
     */
    void deleteAccount(Integer id);
}

我们来写service的实现类,这一层直接调用dao层的方法即可

package com.lp.service.impl;

import com.lp.dao.AccountDao;
import com.lp.domain.Account;
import com.lp.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Date 2020/5/27 16:49
 * @Author luopeng
 */
@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

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

    public Account findById(Integer id) {
        return accountDao.findById(id);
    }

    public void save(Account account) {
        accountDao.save(account);
    }

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

    public void deleteAccount(Integer id) {
        accountDao.deleteAccount(id);
    }
}

再把dap层的实现类代码补上

package com.lp.dao.impl;

import com.lp.dao.AccountDao;
import com.lp.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;

/**
 * @Date 2020/5/27 16:53
 * @Author luopeng
 */
@Repository
public class AccountDaoImpl implements AccountDao {

    @Autowired
    private QueryRunner queryRunner;



    public List<Account> findAllAccount() {
        try {
            return queryRunner.query("select * from account", new BeanListHandler<Account>(Account.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public Account findById(Integer id) {
        try {
            return queryRunner.query("select * from account where id = ?",new BeanHandler<Account>(Account.class),id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        ;
        return null;
    }

    public void save(Account account) {
        try {
            queryRunner.update("insert into account (name,money) values (?,?)",account.getName(),account.getMoney());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

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

    public void deleteAccount(Integer id) {
        try {
            queryRunner.update("delete from account where id = ?",id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

JdbcConfig.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=962464

从这里开始分割,我们先来用xml配合注解的配置方式来做后面部分


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">
<!--声明扫描的包-->
    <context:component-scan base-package="com.lp"/>
<!--导入配置文件-->
    <context:property-placeholder location="JdbcConfig.properties"/>

<!--配置QueryRunner-->
    <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
        <constructor-arg name="ds" ref="dataSource"/>
    </bean>
<!--配置数据源-->
    <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
</beans>

测试类

package com.lp.test;

import com.lp.domain.Account;
import com.lp.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;

/**
 * @Date 2020/5/27 17:25
 * @Author luopeng
 */

@RunWith(value = SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {

    @Autowired
    private AccountService accountService;

    @Test
    public void testFindAll(){
        List<Account> allAccount = accountService.findAllAccount();
        for (Account account : allAccount) {
            System.out.println(account);
        }
    }

    @Test
    public void testFindById(){
        Account account = accountService.findById(2);
        System.out.println(account);
    }

    @Test
    public void testUpdateAccount(){
        Account account = new Account();
        account.setId(2);
        account.setMoney(2000f);
        account.setName("哔哩哔哩");
        accountService.updateAccount(account);
        this.testFindAll();
    }

    @Test
    public void testSaveAccount(){
        Account account = new Account();
        account.setMoney(2500f);
        account.setName("自学");
        accountService.save(account);
        this.testFindAll();
    }

    @Test
    public void testDeleteAccount(){
        accountService.deleteAccount(4);
        this.testFindAll();
    }
}

ok,完成了,我们测试查询得到结果
在这里插入图片描述


现在我们来看看把上面的xml换成纯注解的形式


我们先来个jdbc的配置类JdbcConfig

package config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

/**
 * @Date 2020/5/27 18:05
 * @Author luopeng
 */
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;

    @Bean(name = "runner")
    @Scope("prototype")
    public QueryRunner createQueryRunner(DataSource dataSource){
        return new QueryRunner(dataSource);
    }

    @Bean(name = "dataSource")
    public DataSource createDataSources(){
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        try {
            dataSource.setDriverClass(driver);
            dataSource.setJdbcUrl(url);
            dataSource.setUser(username);
            dataSource.setPassword(password);
            return dataSource;
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
        return dataSource;
    }
}

我们来个SpringConfig配置类

package config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.context.annotation.*;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

/**
 * Configuration
 *              声明这是一个配置类
 * ComponentScan(basePackages = "com.lp")
 *              声明spring自动扫描的包,相当于xml中的
 *                  <context:component-scan base-package="com.lp"/>
 * @Date 2020/5/27 18:05
 * @Author luopeng
 */
//@Configuration
@ComponentScan(basePackages = "com.lp")
@Import(JdbcConfig.class)
@PropertySource("classpath:JdbcConfig.properties")
public class SpringConfig {

}

测试类

package com.lp.test;

import config.SpringConfig;
import com.lp.domain.Account;
import com.lp.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;

/**
 * @Date 2020/5/27 17:25
 * @Author luopeng
 */

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

    @Autowired
    private AccountService accountService;

    @Test
    public void testFindAll(){
        List<Account> allAccount = accountService.findAllAccount();
        for (Account account : allAccount) {
            System.out.println(account);
        }
    }

    @Test
    public void testFindById(){
        Account account = accountService.findById(2);
        System.out.println(account);
    }

    @Test
    public void testUpdateAccount(){
        Account account = new Account();
        account.setId(2);
        account.setMoney(2000f);
        account.setName("哔哩哔哩");
        accountService.updateAccount(account);
        this.testFindAll();
    }

    @Test
    public void testSaveAccount(){
        Account account = new Account();
        account.setMoney(2500f);
        account.setName("自学");
        accountService.save(account);
        this.testFindAll();
    }

    @Test
    public void testDeleteAccount(){
        accountService.deleteAccount(4);
        this.testFindAll();
    }
}

ok,写完了!

其实用配置加上注解的形式来开发会更有效的提高开发效率,因为就算是注解也会在某些地方很复杂,而且还需要你理解更多东西,不比xml简单!对于实际开发应该就情况使用!

猜你喜欢

转载自blog.csdn.net/lp20171401131/article/details/106389460
今日推荐