Spring配置数据源,注解开发

数据源作用

  • 数据源(连接池)是提高程序性能如出现的
  • 事先实例化数据源,初始化部分连接资源
  • 使用连接资源时从数据源中获取
  • 使用完毕后将连接资源归还给数据源
    常见的数据源(连接池):DBCP、C3P0,BoneCP、Druid等

1.1 数据源的开发步骤
① 导入数据源的坐标和数据库驱动坐标(注意版本号,我Mysql是8.0)

<!--导入MySQL-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.20</version>
    </dependency>
<!--    导入C3P0-->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.2</version>
    </dependency>

    <!--    导入druid-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.10</version>
    </dependency>
  </dependencies>

② 创建数据源对象
③ 设置数据源的基本连接数据
④ 使用数据源获取连接资源和归还连接资源(分别是c3p0和bruid)dataSource.setUrl("jdbc:mysql://localhost:3306/mybatis?useSSL=false&serverTimezone=UTC");(很重要 )

public void testC3P0() throws Exception {
//创建数据源
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
//设置数据库连接参数
        dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/mybatis?useSSL=false&serverTimezone=UTC");
        dataSource.setUser("root");
        dataSource.setPassword("123321");
        Connection connection = dataSource.getConnection();
//获得连接对象
        System.out.println(connection);

        connection.close();
    }

 public void testDruid() throws Exception {
//创建数据源
        DruidDataSource dataSource = new DruidDataSource();

        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/mybatis?useSSL=false&serverTimezone=UTC");
        dataSource.setUsername("root");
        dataSource.setPassword("123321");
        DruidPooledConnection connection = dataSource.getConnection();
        System.out.println(connection);

    }

Spring配置数据源

1.2 数据源的手动创建
在resource目录下创建jdbc.properties配置文件
在这里插入图片描述

public void testDruid1() throws Exception {
		//加载类路径下的jdbc.properties
        ResourceBundle rb = ResourceBundle.getBundle("jdbc");
        String driver = rb.getString("driver");
		ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(rb.getString("jdbc.driver"));
//了解即可
    }

上述内容可以通过Spring容器使用,降低耦合
applicationContext.xml文件配置

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
<!--        &要与&amp替换-->
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;serverTimezone=UTC"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123321"></property>
   </bean>

<!--        代码实现-->
public void testDruid2() throws Exception {
        ApplicationContext ap = new ClassPathXmlApplicationContext("applicationContext.xml");
        DataSource bean = ap.getBean(DataSource.class);
        Connection connection = bean.getConnection();
        System.out.println(connection);
        connection.close();
    }

1.3抽取jdbc配置文件
applicationContext.xml加载jdbc.properties配置文件获得连接信息。是通过context:property-placeholder所以要加载context(可通过spring文件自带的bean进行更改)
在这里插入图片描述
代码修改

<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:property-placeholder location="classpath:jdbc.properties"/>

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
<!--        &要与&amp替换-->
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;serverTimezone=UTC"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123321"></property>

<!--        <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>

在这里插入图片描述

Spring注解开发

2.1 Spring原始注解:Spring原始注解主要是替代的配置
在这里插入图片描述

使用注解进行开发时,需要在applicationContext.xml中配置组件扫描,作用是指定哪个包及其子包下Bean需要进行扫描以便识别使用注解配置的类、字段和方法。<context:component-scan base-package="com.ithema"/>

将上述代码进行注解开发
dao层使用@Compont或@Repository标识UserDaoImpl需要Spring进行实例化。
在这里插入图片描述
service层

package com.ithema.service.impl;

import com.ithema.dao.UserDao;
import com.ithema.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

//import javax.annotation.PostConstruct;
//import javax.annotation.PreDestroy;
//import javax.annotation.Resource;

//<bean id="userService" class="com.itheima.service.impl.UserServiceImpl">
//@Component("userService")
@Service("userService")
//@Scope("prototype")
@Scope("singleton")
public class UserServiceImpl implements UserService {

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

    //<property name="userDao" ref="userDao"></property>
    @Autowired //按照数据类型从Spring容器中进行匹配的
    @Qualifier("userDao")  //是按照id值从容器中进行匹配的 但是主要此处@Qualifier结合@Autowired一起使用
//    @Resource(name="userDao") //@Resource相当于@Qualifier+@Autowired
    private UserDao userDao;

    public void save() {
        System.out.println(driver);
        userDao.save();
    }

//    @PostConstruct
//    public void init(){
//        System.out.println("Service对象的初始化方法");
//    }
//
//    @PreDestroy
//    public void destory(){
//        System.out.println("Service对象的销毁方法");
//    }

}

在application Context.xml文件内配置包扫描

 <context:component-scan base-package="com.ithema"/>

实现方法

 public static void main(String[] args) {
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = app.getBean(UserService.class);
        userService.save();
    }

新注解开发

在这里插入图片描述
方法实现:创建两个类随便命名,其中一个是替代spring核心配置容器
在这里插入图片描述
SpringConfiguration类中

package com.ithema.config;
import org.springframework.context.annotation.*;
@Configuration
@ComponentScan("com.ithema")
@Import(DataSourceConfiguration.class)
public class SpringConfigration {

}

DataSourceConfiguration.class

package com.ithema.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.PropertySource;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;

@PropertySource("classpath:jdbc.properties")

public class DataSourceConfiguration {
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
    @Bean("dataSource")
    public DataSource getDataSource() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(driver);
        dataSource.setJdbcUrl(url);
        dataSource.setUser(username);
        dataSource.setPassword(password);
        return dataSource;
    }


}

实现需要使用 ApplicationContext app = new AnnotationConfigApplicationContext(SpringConfigration.class); 创建对象

 public static void main(String[] args) {
        //ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        ApplicationContext app = new AnnotationConfigApplicationContext(SpringConfigration.class);
        UserService userService = app.getBean(UserService.class);
        userService.save();
        //app.close();
    }

成功信息输出在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值