springboot学习(一)IDEA简单使用以及数据源配置的三种方法

1 运行环境

IDEA、maven

2 maven的配置如下

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing,
  software distributed under the License is distributed on an
  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  KIND, either express or implied.  See the License for the
  specific language governing permissions and limitations
  under the License.
-->
<!-- $Id: pom.xml 642118 2008-03-28 08:04:16Z reinhard $ -->
<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/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <packaging>war</packaging>

  <name>SpringBoot</name>
  <groupId>com.darksouls</groupId>
  <artifactId>SpringBoot</artifactId>
  <version>1.0-SNAPSHOT</version>

    <!--springboot父类依赖-->
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.4.RELEASE</version>
  </parent>

  <build>
    <plugins>
      <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>maven-jetty-plugin</artifactId>
        <version>6.1.7</version>
        <configuration>
          <connectors>
            <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
              <port>8888</port>
              <maxIdleTime>30000</maxIdleTime>
            </connector>
          </connectors>
          <webAppSourceDirectory>${project.build.directory}/${pom.artifactId}-${pom.version}</webAppSourceDirectory>
          <contextPath>/</contextPath>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <!--dependency>
      <groupId>com.darksouls</groupId>
      <artifactId>[the artifact id of the block to be mounted]</artifactId>
      <version>1.0-SNAPSHOT</version>
    </dependency-->

      <!--springboot的主要包-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

      <!--DRUID是阿里巴巴开源平台上一个数据库连接池实现-->
    <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.19</version>
    </dependency>
      <!--数据库连接-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.12</version>
    </dependency>
  </dependencies>

</project>

如上述代码中有标签,是版本控制的一种方式,控制springboot版本的一种方式

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.4.RELEASE</version>
  </parent>
    <!--springboot的主要包-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

在我看来springboot相当于将spring很多组件的jar包都放在了这一个中,如下图可见(仅是部分jar包)已经导入了springboot主要组件(如beans、aop、core…)对于spring熟悉的人这些在spring配置的时候需要分开配置
在这里插入图片描述

3 如何使用springboot

在这里插入图片描述
如上图所示,与ssm框架下没有太大区别,但是启动方式有很大区别了
首先是SpringBootDemo作为启动,springboot会自动启动tocat
SpringBootDemo.java代码如下:

package com.darksouls;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootDemo {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootDemo.class,args);
    }
}

然后是controller层(原谅我为了方便没有创建多个包),这样就构成了一个简单的应答,
MyController:

package com.darksouls;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.sql.DataSource;


@Controller
public class MyController {
    /**
     * 自动注入数据源配置
     */
    @Autowired
    private DataSource dataSource;

    /**
     * @RequestMapping 和 @GetMapping @PostMapping 区别:
     * https://blog.csdn.net/ziany/article/details/80541311
     * @return
     */
    @GetMapping("out")
    @ResponseBody
    public String out(){
        return "Hello Spring Boot";
    }
}

启动一下:就会显示下图在这里插入图片描述

4.配置数据源

在数据层,JDBC连接是必须的,所有就有了对数据源的配置,在ssm框架中
例如下图,jdbc.properties中就保存了连接数据库需要的信息
在这里插入图片描述
如何检查配置是否正确:
启动的时候选择debug启动在下图加断点,然后访问这个url在这里插入图片描述
在debug可以看到:
在这里插入图片描述

4.1基本的配置方法

创建一个新的java类,导入配置文件就然后el表达式就可以从配置文件中读出数据库连接的基本信息
MyConfig.java类:

package com.darksouls.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;
import javax.xml.crypto.Data;

@Configuration
/**
 * 第一种:基本配置导入配置文件
 */
@PropertySource("classpath:jdbc.properties")
public class MyConfig {
    @Value("${jdbc.driverclass}")
    private String driverClass;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
    @Bean
    public DataSource dateSources(){
       DruidDataSource dataSource =  new DruidDataSource();
       dataSource.setDriverClassName(driverClass);
       dataSource.setUrl(url);
       dataSource.setUsername(username);
       dataSource.setPassword(password);
       return dataSource;
    }
    
  }

4.2springboot对数据源配置的优化(第一种)

再创建一个新的java类DBprop.java,不再通过导入数据源配置文件,使用spring默认的配置文件application.properties:


#第一种第二种的配置文件内容
#jdbc.driverclass=com.mysql.cj.jdbc.Driver
#jdbc.url=jdbc:mysql://localhost:3306/mytest
#jdbc.username=root
#jdbc.password=root

#第三种的配置文件
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mytest
jdbc.username=root
jdbc.password=root

在这里插入图片描述
DBprop.java

package com.darksouls.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * ‘在这些变量前面都加jdbc
 */
@ConfigurationProperties(prefix = "jdbc")
/**
 * 实例化DBprop
 */
@Component
public class DBprop {

        private String driverClass;

        private String url;

        private String username;

        private String password;

    public String getDriverClass() {
        return driverClass;
    }

    public void setDriverClass(String driverClass) {
        this.driverClass = driverClass;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

MyConfig.java

package com.darksouls.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;
import javax.xml.crypto.Data;
@Configuration
public class MyConfig {
    @Bean
    public DataSource dateSources(DBprop prop){
        DruidDataSource dataSource =  new DruidDataSource();
        dataSource.setDriverClassName(prop.getDriverClass());
        dataSource.setUrl(prop.getUrl());
        dataSource.setUsername(prop.getUsername());
        dataSource.setPassword(prop.getPassword());
        return dataSource;
    }
 }

4.3 springboot对数据源的优化(第二种)

不需要DBprop,实现自动装配,是最简单的一种,但是DruidDataSource对象一定的属性名一定要和application.properties中的变量名相同
application.properties文件代码如下:


#第一种第二种的配置文件内容
#jdbc.driverclass=com.mysql.cj.jdbc.Driver
#jdbc.url=jdbc:mysql://localhost:3306/mytest
#jdbc.username=root
#jdbc.password=root

#第三种的配置文件
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mytest
jdbc.username=root
jdbc.password=root
public class MyConfig {
   @Bean
   @ConfigurationProperties(prefix = "jdbc")
   public DataSource dataSource(){
       return new DruidDataSource();
   }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值