采用纯注解把Spring、JdbcTemplate、druid、JUnit进行框架整合

4 篇文章 0 订阅
3 篇文章 0 订阅

在这里插入图片描述

maven依赖


    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>
        <!-- Spring依赖 -->
        <!-- 1.Spring核心依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>
        <!-- 2.Spring dao依赖 -->
        <!-- spring-jdbc包括了一些如jdbcTemplate的工具类 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>
        <!-- 3.Spring web依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>
        <!-- 4.Spring test依赖:方便做单元测试和集成测试 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.21</version>
        </dependency>
        <!--druid依赖-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.9</version>
        </dependency>
        <!--mysql 依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.25</version>
        </dependency>


    </dependencies>

domain 实例类

package com.chensy.springAndJdbcTemplateFullAnnotation.domain;

import java.io.Serializable;

public class Customer implements Serializable {
    private Long cust_id;
    private String cust_name;
    private String cust_source;
    private String cust_industry;
    private String cust_level;
    private String cust_address;
    private String cust_phone;

    public Long getCust_id() {
        return cust_id;
    }

    public void setCust_id(Long cust_id) {
        this.cust_id = cust_id;
    }

    public String getCust_name() {
        return cust_name;
    }

    public void setCust_name(String cust_name) {
        this.cust_name = cust_name;
    }

    public String getCust_source() {
        return cust_source;
    }

    public void setCust_source(String cust_source) {
        this.cust_source = cust_source;
    }

    public String getCust_industry() {
        return cust_industry;
    }

    public void setCust_industry(String cust_industry) {
        this.cust_industry = cust_industry;
    }

    public String getCust_level() {
        return cust_level;
    }

    public void setCust_level(String cust_level) {
        this.cust_level = cust_level;
    }

    public String getCust_address() {
        return cust_address;
    }

    public void setCust_address(String cust_address) {
        this.cust_address = cust_address;
    }

    public String getCust_phone() {
        return cust_phone;
    }

    public void setCust_phone(String cust_phone) {
        this.cust_phone = cust_phone;
    }

    @Override
    public String toString() {
        return "com.chensy.cus.domain.Customer{" +
                "cust_id=" + cust_id +
                ", cust_name='" + cust_name + '\'' +
                ", cust_source='" + cust_source + '\'' +
                ", cust_industry='" + cust_industry + '\'' +
                ", cust_level='" + cust_level + '\'' +
                ", cust_address='" + cust_address + '\'' +
                ", cust_phone='" + cust_phone + '\'' +
                '}';
    }
}

dao
CustomerDao接口:

package com.chensy.springAndJdbcTemplateFullAnnotation.dao;

import com.chensy.cusxml.domain.Customer;

import java.util.List;

public interface CustomerDao {
    List<Customer> findAll();
}

dao impl
CustomerDaoImpl:

package com.chensy.springAndJdbcTemplateFullAnnotation.dao.impl;

import com.chensy.cusxml.dao.CustomerDao;
import com.chensy.cusxml.domain.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository("customerDao")
public class CustomerDaoImpl implements CustomerDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;//不需要实例化,通过spring依赖注入进来,采用xml配置,需要提供set方法


    public List<Customer> findAll() {
        String sql ="select * from cst_customer";
        List<Customer> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Customer>(Customer.class));

        return list;
    }
}

service
CustomerService接口:

package com.chensy.springAndJdbcTemplateFullAnnotation.service;

import com.chensy.cusxml.domain.Customer;

import java.util.List;

public interface CustomerService {
    /**
     * 业务层:查询所有客户
     * @return
     */
    List<Customer> findAllCustomer();
}

impl实现类
CustomerServiceImpl

package com.chensy.springAndJdbcTemplateFullAnnotation.service.impl;

import com.chensy.cusxml.dao.CustomerDao;
import com.chensy.cusxml.domain.Customer;
import com.chensy.cusxml.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("customerService")
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private CustomerDao customerDao;//不需要实例化,通过spring依赖注入,采用xml配置,需提供set方法



    public List<Customer> findAllCustomer() {
        List<Customer> list = customerDao.findAll();
        return list;
    }
    /**
     * 在类上加@Service注解,在customerDao上加@Autowired注解,表示给该属性注入值
     */
}

mysql 测试数据

CREATE TABLE `cst_customer` (
  `cust_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '客户编号(主键)',
  `cust_name` varchar(32) NOT NULL COMMENT '客户名称(公司名称)',
  `cust_source` varchar(32) DEFAULT NULL COMMENT '客户信息来源',
  `cust_industry` varchar(32) DEFAULT NULL COMMENT '客户所属行业',
  `cust_level` varchar(32) DEFAULT NULL COMMENT '客户级别',
  `cust_address` varchar(128) DEFAULT NULL COMMENT '客户联系地址',
  `cust_phone` varchar(64) DEFAULT NULL COMMENT '客户联系电话',
  PRIMARY KEY (`cust_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

insert into `cst_customer` (`cust_id`, `cust_name`, `cust_source`, `cust_industry`, `cust_level`, `cust_phone`, `cust_address`) values('1','阿里巴巴','6','1','22','8650000','杭州');
insert into `cst_customer` (`cust_id`, `cust_name`, `cust_source`, `cust_industry`, `cust_level`, `cust_phone`, `cust_address`) values('2','百度集团','7','2','23','8650001','北京');
insert into `cst_customer` (`cust_id`, `cust_name`, `cust_source`, `cust_industry`, `cust_level`, `cust_phone`, `cust_address`) values('3','腾讯科技','6','3','22','8650123','深圳');
insert into `cst_customer` (`cust_id`, `cust_name`, `cust_source`, `cust_industry`, `cust_level`, `cust_phone`, `cust_address`) values('4','网易科技','7','4','23','8650009','北京');
insert into `cst_customer` (`cust_id`, `cust_name`, `cust_source`, `cust_industry`, `cust_level`, `cust_phone`, `cust_address`) values('5','小米科技','7','5','23','8650110','北京');
insert into `cst_customer` (`cust_id`, `cust_name`, `cust_source`, `cust_industry`, `cust_level`, `cust_phone`, `cust_address`) values('6','华为科技','7','5','23','8650890','深圳');
insert into `cst_customer` (`cust_id`, `cust_name`, `cust_source`, `cust_industry`, `cust_level`, `cust_phone`, `cust_address`) values('7','美的集团','6','4','22','8650765','广东');
insert into `cst_customer` (`cust_id`, `cust_name`, `cust_source`, `cust_industry`, `cust_level`, `cust_phone`, `cust_address`) values('8','格力空调','6','3','23','8650456','广东');
insert into `cst_customer` (`cust_id`, `cust_name`, `cust_source`, `cust_industry`, `cust_level`, `cust_phone`, `cust_address`) values('9','万科集团','6','2','22','8650115','广东');
insert into `cst_customer` (`cust_id`, `cust_name`, `cust_source`, `cust_industry`, `cust_level`, `cust_phone`, `cust_address`) values('10','恒大集团','7','1','23','8650127','广州');

select * from cst_customer;

在这里插入图片描述
现在准备工作已经准备完成

1.创建配置类

创建Spring的配置类SpringConfig
在这里插入图片描述

SpringConfig

package com.chensy.springAndJdbcTemplateFullAnnotation.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration //指定该类是一个配置类,等价于一个spring的配置文件
@ComponentScan(basePackages = "com.chensy.springAndJdbcTemplateFullAnnotation")
@Import(JdbcConfig.class)
public class SpringConfig {


}

2.创建jdbc配置类

在这里插入图片描述

JdbcConfig

package com.chensy.springAndJdbcTemplateFullAnnotation.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
@PropertySource("classpath:jdbc.properties")
public class JdbcConfig {
    /**
     * Bean注解:该注解只能写在方法上,表明使用此方法创建一个对象,
     * 并且放入spring容器中。
     * name属性:给当前的@Bean注解方法创建的对象指定一个名称(即bean的id)
     *
     */
    @Value("${jdbc.driverClass}")
    private String driver;

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

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

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






    @Bean(name = "dataSource")
    public DataSource createDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean(name = "jdbcTemplate")
    public JdbcTemplate createJdbcTemplate(DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }
}

3.引入jdbc属性文件

创建jdbc属性文件
在这里插入图片描述

jdbc.properties

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///test?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456

4.测试

package test;

import com.chensy.cusxml.domain.Customer;
import com.chensy.cusxml.service.CustomerService;
import com.chensy.springAndJdbcTemplateFullAnnotation.config.SpringConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

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

    @Autowired
    private CustomerService customerService;

    
    @Test
    public void test3(){
        //AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class);
        //CustomerService customerService = (CustomerService) ac.getBean("customerService");
        List<Customer> list = customerService.findAllCustomer();
        for (Customer customer : list) {
            System.out.println(customer);
        }
    }
}

运行结果:
在这里插入图片描述

5.小结:新注解说明

5.1.@Configuration

作用:

用于指定当前类是一个spring配置类,当创建容器时会从该类上加载注解。获取容器时需要使用AnnotationApplicationContext(有@Configuration注解的类.class)。

属性:

value:用于指定配置类的字节码

5.2.@ComponentScan

作用:

用于指定spring在初始化容器时要扫描的包。作用和在spring的xml配置文件中的:

<context:component-scan base-package=“com.itheima”/>是一样的。

属性:

basePackages:用于指定要扫描的包。和该注解中的value属性作用一样。

5.3.@Bean

作用:

该注解只能写在方法上,表明使用此方法创建一个对象,并且放入spring容器。

属性:

name:给当前@Bean注解方法创建的对象指定一个名称(即bean的id)。

5.4.@PropertySource

作用:

用于加载.properties文件中的配置。例如我们配置数据源时,可以把连接数据库的信息写到properties配置文件中,就可以使用此注解指定properties配置文件的位置。

属性:

value[]:用于指定properties文件位置。如果是在类路径下,需要写上classpath。

5.5.@Import

作用:

用于导入其他配置类,在引入其他配置类时,可以不用再写@Configuration注解。当然,写上也没问题。

属性:

value[]:用于指定其他配置类的字节码。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值