spring配置数据源

z# 1.spring配置数据源
1.1数据源(连接池)的作用

  • 数据源(连接池)是用来提高程序性能的
  • 事先实例化数据源,初始化部分连接资源
  • 使用连接资源时从数据源获取
  • 使用完毕后将连接资源归还给数据源
    常见的数据源(连接池)DBCP,C3P0,BoneCP,Druid等
    1.2数据源连接数据库实例展示
    c3p0连接数据库展示
    @Test
    /**
     * 手动建立c3p0连接池
     */
    public void text1() throws PropertyVetoException, SQLException {
        //创建数据源对象
        ComboPooledDataSource dataSource=new ComboPooledDataSource();
        //设置基本连接信息
        dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/one?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8");
        dataSource.setUser("root");
        dataSource.setPassword("root");
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        //释放资源
        connection.close();
    }

druid连接池

   @Test
    /**
     * 手动建立Druid连接池
     */
    public  void text2() throws SQLException {
        DruidDataSource dataSource=new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/one?serverTimezone=UTC");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        DruidPooledConnection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }

将参数抽取3到配置文件

  • 建立一个.properties的文件,写配置信息
    例如:我建立一个jdbc.properties的配置文件
driver =  com.mysql.cj.jdbc.Drive
url = jdbc:mysql://localhost:3306/one?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8
username = root
paaaword = root

2.获取配置文件的信息连接数据库

   @Test
    public void text3() throws PropertyVetoException, SQLException {
        ResourceBundle resourceBundle=ResourceBundle.getBundle("jdbc");//基本名称(基名即去掉后缀)
        String driver = resourceBundle.getString("driver");
        String url = resourceBundle.getString("url");
        String username = resourceBundle.getString("username");
        String paaaword = resourceBundle.getString("paaaword");
        ComboPooledDataSource dataSource=new ComboPooledDataSource();
        dataSource.setDriverClass(driver);
        dataSource.setJdbcUrl(url);
        dataSource.setUser(username);
        dataSource.setPassword(paaaword);
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }

1.3spring配置数据源
可以将DataSource的创建权交由spring容器去完成、
c3p0方式
   1.写注入

<bean id="jdbc" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="DriverClass" value="com.mysql.cj.jdbc.Driver"></property>
    <property name="JdbcUrl" value="jdbc:mysql://localhost:3306/one?serverTimezone=UTC"></property>
    <property name="User" value="root"></property>
    <property name="Password" value="root"></property>
</bean>

   2连接

    @Test
    public void text4() throws SQLException {
        ApplicationContext application = new ClassPathXmlApplicationContext("application.xml");
        DataSource jdbc =(DataSource) application.getBean("jdbc");
        Connection connection = jdbc.getConnection();
        System.out.println(connection);
        connection.close();
    }

2.spring注解开发

2.1原始注解
Spring是轻代码而重配置的框架,配置比较繁重,影响开发效率,所以注解开发是一种趋势,注解代替XML的配置文件可以简化配置,提高开发效率。
Spring的原始注解主要是替代的配置

注解说明
@Component使用在类上用于 实例化Bean
@Controller使用在Web层类上用于实例化Bean
@Server使用在service层类上用于实例化Bean
@Repository使用在Dao层类上用于实例化Bean
@Autowried使用在字段上用于根据类型依赖注入
@Qualifier结合@Autowried一起使用用于根据名称进行注入
@Resource相当于@Autowried+@Qualifier,按照名称进行注入
@Value注入普通属性
@Scope标注Bean的作用范围
@PostConstruct使用在方法上标注该方法是Bean的初始化方法
@PreDestroy使用在方法上标记该方法是Bean的销毁方法

加上自动扫描注解

 <context:component-scan base-package="com.blb(包名)"></context:component-scan>

2.2spring新注解
使用上面的注解还不能全部代替xml配置文件,还需要使用注解代替的配置如下:

  • 非定义的Bean的配置:
  • 加载properties文件的配置:< context:property-placeholder >
  • 组件扫描配置:< context:component-scan >
  • 引入其他文件:< import >
注解说明
@Configuration指定当前类是一个spring配置类,当创建容器时会从该类上加载注解
@ComponentScan用于指定Spring在初始化容器时要扫描的包
作用和spring的xml配置文件中的 <context:component-scan base-package=“com.blb”></context:component-scan>一样
@Bean使用在方法上,标注将该方法的返回值存储到spring容器中
@PropertySource用于加载properties文件中的屏配置
@Import用于导入其他配置类

样例展示

package com.blb.Config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

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

@Configuration
@ComponentScan("com.blb")
@PropertySource("jdbc.properties")
public class SpringConfig {
    @Value("${driver}")
    private String driver;
    @Value("${url}")
    private String url;
    @Value("${user}")
    private String name;
    @Value("${psaaword}")
    private String password;

    @Bean("jdbcData")
    public DataSource getDataSource() throws PropertyVetoException {
        ComboPooledDataSource dataSource=new ComboPooledDataSource();
        dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/one?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8");
        dataSource.setUser("root");
        dataSource.setPassword("199866");
        return dataSource;
    }
    @Bean("jdbcData1")
    public DataSource getDataSource1() throws PropertyVetoException {
        ComboPooledDataSource dataSource=new ComboPooledDataSource();
        dataSource.setDriverClass(driver);
        dataSource.setJdbcUrl(url);
        dataSource.setUser(name);
        dataSource.setPassword(password);
        return dataSource;
    }
}

3.spring集成Junit

1.3spring集成Junit概念
在测试类中,每个测试方法都有一下两行代码

 ApplicationContext applicationContext=new ClassPathXmlApplicationContext("application.xml");
        DataSource jdbcData =(DataSource) applicationContext.getBean("jdbcData");

这两行代码的作用是获取容器,如果不写会直接提示空指针异常,所有有不能轻易删掉
3.2上述问题的解决思路

  1. 让SpringJunit负责创建spring容器,但是需要将配置文件的名称告诉它
  2. 将需要进行测试的bean直接在测试类中进行注入

3.3spring集成Junit的步骤

  1. 导入spring集成Junit的坐标
 <dependency>
           <groupId>junit</groupId>
           <artifactId>junit</artifactId>
           <version>4.9</version>
           <scope>test</scope>
       </dependency>
        <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-test</artifactId>
           <version>5.2.12.RELEASE</version>
       </dependency>
  1. 使用@Runwith注解代替原来的运行期
  2. 使用@ContextConfiguration指定配置文件‘或配置类
  3. 使用@Autowried
  4. 创建测试方法进行测试
    参考代码:参考代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值