Spring初识(二)

一、Xml方式访问数据库


1.1 Spring的JdbcTemplate

Spring的JdbcTemplate(了解会用) ​ 在Spring中提供了一个可以操作数据库的对象org.springframework.jdbc.core.JdbcTemplate,对象封装了jdbc技术,JDBC的模板对象与DBUtils中的QueryRunner非常相似.

测试: 在pom.xml中导入依赖

             <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>5.3.10</version>
            </dependency>

1.2 创建user表并添加数据

 

1.3 pom.xml导入相关依赖

<?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.coffee</groupId>
    <artifactId>spring-02</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.26</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.10</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.10</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.9</version>
        </dependency>
        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>javax.annotation-api</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
        </dependency>
    </dependencies>
</project>

1.3 编写pojo

package com.coffee.entity;

import lombok.Data;

@Data
public class Student {
    private Integer id;
    private String name;
    private String age;
}

1.4 编写UserDao以及UserDaoImpl

package com.coffee.mapper;

import com.coffee.entity.Student;

import java.util.List;

public interface StudentMapper {
    List<Student> find();
}
package com.coffee.mapper.mapperImpl;

import com.coffee.entity.Student;
import com.coffee.mapper.StudentMapper;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;


public class StudentMapperImpl implements StudentMapper {

    private JdbcTemplate jdbcTemplate;

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

    @Override
    public List<Student> find() {
        String sql = "select * from student";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<Student>(Student.class));
    }
}

1.5 编写UserService以及UserServiceImpl

package com.coffee.service;

import com.coffee.entity.Student;

import java.util.List;

public interface StudentService {
    List<Student> find();
}
package com.coffee.service.impl;

import com.coffee.entity.Student;
import com.coffee.mapper.mapperImpl.StudentMapperImpl;
import com.coffee.service.StudentService;

import java.util.List;

public class StudentServiceImpl implements StudentService {

    private StudentMapperImpl studentMapper;

    public void setStudentMapper(StudentMapperImpl studentMapper) {
        this.studentMapper = studentMapper;
    }

    @Override
    public List<Student> find() {
        return studentMapper.find();
    }
}

1.6 编写UserController

package com.coffee.controller;

import com.coffee.entity.Student;
import com.coffee.service.impl.StudentServiceImpl;

import java.util.List;

public class StudentController {

    private StudentServiceImpl studentService;

    public void setStudentService(StudentServiceImpl studentService) {
        this.studentService = studentService;
    }

    public List<Student> find(){
        return studentService.find();
    }
}

1.7 jdbc.properties配置文件

db.driverClassName = com.mysql.cj.jdbc.Driver
db.url = jdbc:mysql://localhost:3306/javacoffee?serverTimezone=Asia/Shanghai&characterEncoding=UTF8
db.username=root
db.password=1234

1.8 applicationContext.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:util="http://www.springframework.org/schema/util"
       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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">
<!--    扫描properties文件-->
    <context:property-placeholder location="db.properties"></context:property-placeholder>
<!--    获取druid连接池的datasource对象 并注入数据-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="username" value="${db.username}"></property>
        <property name="password" value="${db.password}"></property>
        <property name="url" value="${db.url}"></property>
        <property name="driverClassName" value="${db.driverClassName}"></property>
    </bean>

<!--获取spring中的jdbcTemplate对象,并把datasource注入-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
<!--dao层获取studentMapper对象 并注入jdbcTemplate-->
    <bean id="studentMapper" class="com.coffee.mapper.mapperImpl.StudentMapperImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
    </bean>
<!--service层 获取studentService对象,并注入studentMapper-->
    <bean id="studentService" class="com.coffee.service.impl.StudentServiceImpl">
        <property name="studentMapper" ref="studentMapper"></property>
    </bean>
<!--controller层 获取studentController对象 并注入studentService-->
    <bean id="studentController" class="com.coffee.controller.StudentController">
        <property name="studentService" ref="studentService"></property>
    </bean>
</beans>

1.9 测试

import com.coffee.controller.StudentController;
import com.coffee.entity.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class Test {
    @org.junit.Test
    public void myTest(){
        ApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");
        StudentController studentController =(StudentController) applicationContext.getBean("studentController");
        List<Student> students = studentController.find();
        for (Student student : students) {
            System.out.println(student);
        }
    }
}

结果如下:

二、注解方式访问数据库


2.1 Spring中的注解

@Configuration ​ 作用:指定当前类是一个配置类 ​ 细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写。 

@ComponentScan 作用:用于通过注解指定spring在创建容器时要扫描的包 属性:value:它和basePackages的作用是一样的,都是用于指定创建容器时要扫描的包。 等同于xml中: <context:component-scan base-package="com.qf"/>

@PropertySource 作用:用于指定properties文件的位置 属性:value:指定文件的名称和路径。 关键字:classpath,表示类路径下

等同于xml中: <context:property-placeholder location="classpath:jdbc.properties"/>

@Bean ​ 作用:用于把当前方法的返回值作为bean对象存入spring的ioc容器中 ​ 属性:name:用于指定bean的id。当不写时,默认值是当前方法的名称 ​ 细节:当我们使用注解配置方法时,如果方法有参数,在参数前加:@Qualifier("@Bean注解中name的值"),spring框架会去容器中查找有没有可用的bean对象查找的方式和Autowired注解的作用是一样的。

@Import ​ 作用:用于导入其他的配置类 ​ 属性:value:用于指定字节码。 其他配置类的​ 当我们使用Import的注解之后,有Import注解的类就父配置类,而导入的都是子配置类

等同于xml中: <import resource="xxx.xml"></import>

2.2 创建pojo,dao,service,controller

使用@Repository,@Service,@Controller以及@Autowired 配置所需代码

2.2.1 pojo实体类

package com.coffee.entity;

import lombok.Data;

@Data
public class Student {
    private Integer id;
    private String name;
    private String age;
}

2.2.2  dao

package com.coffee.dao;

import com.coffee.entity.Student;

import java.util.List;

public interface StudentDao {
    public List<Student> find();
}
package com.coffee.dao.impl;

import com.coffee.dao.StudentDao;
import com.coffee.entity.Student;
import com.coffee.jdbcUtil.SpringJdbcTemp;
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
public class StudentDaoImpl implements StudentDao {
    //注入
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<Student> find() {
        String sql = "select * from test1";
        System.out.println(jdbcTemplate);
        List<Student> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Student>(Student.class));
        return query;
    }
}

2.2.3 service

package com.coffee.service;

import com.coffee.entity.Student;

import java.util.List;

public interface StudentService {
    List<Student> find();
}
package com.coffee.service.impl;

import com.coffee.dao.StudentDao;
import com.coffee.entity.Student;
import com.coffee.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentDao studentDao;
    @Override
    public List<Student> find() {
        System.out.println(studentDao);
        return studentDao.find();

    }
}

2.2.4 controller

package com.coffee.controller;

import com.coffee.entity.Student;
import com.coffee.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.util.List;
@Controller
public class FindStudent {
    @Autowired
    private StudentService studentService;

    public List<Student> find(){
      return studentService.find();
    }
}

2.3 创建db.properties 和 db1.properties配置文件

db.driverClassName = com.mysql.cj.jdbc.Driver
db.url = jdbc:mysql://localhost:3306/javacoffee?serverTimezone=Asia/Shanghai&characterEncoding=UTF8
db.username=root
db.password=1234
db1.driverClassName = com.mysql.cj.jdbc.Driver
db1.url = jdbc:mysql://localhost:3306/javaqwz?serverTimezone=Asia/Shanghai&characterEncoding=UTF8
db1.username=root
db1.password=1234

2.4 创建db 类(我是将获取datasource 和 获取jdbcTemplate分开写了,方便对多个数据库进行操作,换的时候只需要修改sql和参数就行)

package com.coffee.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.stereotype.Repository;
import javax.sql.DataSource;
import java.util.Properties;

@Repository
@PropertySource({"db1.properties","db.properties"}) //读取文件
public class Db {


    //注入数据
    @Value("${db.username}")
    private String username;
    @Value("${db.password}")
    private String password;
    @Value("${db.url}")
    private String url;
    @Value("${db.driverClassName}")
    private String driverClassName;

    //注入数据
    @Value("${db1.username}")
    private String username1;
    @Value("${db1.password}")
    private String password1;
    @Value("${db1.url}")
    private String url1;
    @Value("${db1.driverClassName}")
    private String driverClassName1;




    public DataSource getDataSource() {
        //新建一个properties文件,并赋值
        Properties properties = new Properties();
        properties.setProperty("username", username);
        properties.setProperty("password", password);
        properties.setProperty("url", url);
        properties.setProperty("driverClassName", driverClassName);
        try {
            return DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new RuntimeException("加载错误");
    }

    public DataSource getDataSource1() {
        //新建一个properties文件,并赋值
        Properties properties = new Properties();
        properties.setProperty("username", username1);
        properties.setProperty("password", password1);
        properties.setProperty("url", url1);
        properties.setProperty("driverClassName", driverClassName1);
        try {
            return DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new RuntimeException("加载错误");
    }


}

2.5 创建SpringConfiguration.java作为注解配置类,它的作用和bean.xml是一样的

package com.coffee.jdbcUtil;


import com.coffee.util.Db;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;


@Configuration //设置本类为配置类 提前加载
@ComponentScan("com.coffee")  //扫描
public class SpringJdbcTemp  {
    @Autowired
    private Db db;
    @Bean
    public JdbcTemplate getJdbcTemplate(){
        return new JdbcTemplate(db.getDataSource1());
    }
}

2.6 使用Spring整合junit测试

import com.coffee.controller.FindStudent;
import com.coffee.entity.Student;
import com.coffee.jdbcUtil.SpringJdbcTemp;
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;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringJdbcTemp.class)
public class Test {
    @Autowired
    private FindStudent findStudent;

    @org.junit.Test
    public void test(){
        List<Student> students = findStudent.find();

        for (Student student : students) {
            System.out.println(student);
        }
    }

}

2.6.1 导入spring整合junit坐标

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

2.6.2 使用Junit提供的一个注解把原有的main方法替换了,替换成spring提供的

@RunWith(SpringJUnit4ClassRunner.class)

2.6.3 告知spring的运行器,spring和ioc创建是基于xml还是注解的,并且说明位置

@ContextConfiguration(locations = "classpath:applicationContext.xml") locations:指定xml文件的位置,classpath关键字表示在类路径下

@ContextConfiguration(classes = SpringConfiguration.class) classes:指定注解配置类(需要手动编写配置类)

注意:当我们使用spring 5.x版本的时候,要求junit的jar必须是4.12及以上,spring版本必须保持一致

结果(db.properties文件)

 (db1.properties)文件

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

宇智波波奶茶

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

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

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

打赏作者

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

抵扣说明:

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

余额充值