SpringBoot入门学习

1. SpringBoot概述

1.1 为什么要学习SpringBoot

java一直被人诟病的一点就是臃肿、麻烦。当我们还在辛苦的搭建项目时,可能Python程序员已经把功能写好了,究其原因主要是两点:

  • 复杂的配置
    项目各种配置其实是开发时的损耗, 因为在思考 Spring 特性配置和解决业务问题之间需要进行思维切换,所以写配置挤占了写应用程序逻辑的时间。
  • 混乱的依赖管理
    项目的依赖管理也是件吃力不讨好的事情。决定项目里要用哪些库就已经够让人头痛的了,你还要知道这些库的哪个版本和其他库不会有冲突,这也是件棘手的问题。并且,依赖管理也是一种损耗,添加依赖不是写应用程序代码。一旦选错了依赖的版本,随之而来的不兼容问题毫无疑问会是生产力杀手。

1.2 SpringBoot的特点

①创建独立的Spring应用程序

②直接内嵌tomcat、jetty和undertdow(不需要打war包部署)

③提供了固定化”starter”配置,以简化构建配置

④尽可能的自动配置spring和第三方库

⑤提供产品级的功能,如:安全指标、运行状况检测和外部化配置等。

⑥绝对不会生成代码,并且不需要XML配置

总结:Spring Boot为所有Spring开发者提供了一个开箱即用、非常快熟、广泛接受的入门体验。

2. SpringBoot快速入门

2.1 创建Maven工程

2.2 配置pom.xml文件

 <!--所有的SpringBoot应用都要以该工程作为父工程-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.RELEASE</version>
    </parent>
    <!--启动器:每一个启动器都集成了大量的依赖。(这是一个Web启动器)-->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

2.3 编写HelloController测试

package cn.lingnan.spirngboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController//该注解相当于集成了@Controller和@ResponseBody注解
@RequestMapping("test")
@EnableAutoConfiguration //声明启动自动配置
public class HelloController {

    @GetMapping("method")
    public String method() {
        return "Spring Boot TestDemo";
    }

public static void main(String[] args) {
    //启动固定写法
        SpringApplication.run(HelloController.class, args);
    }
}

3. 优化快速入门(2的延续)

配置一个引导类用于访问所有的Controller和Service,在自动配置中会配置引导类下的所有注解信息

3.1TestApplicationRun(引导类)

package cn.lingnan.spirngboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;



/**
 * 引导类 : Spring Boot应用入口
 */
@EnableAutoConfiguration// 启动SpringBoot应用的自动配置
@ComponentScan // 类似于<context:compoent-scan base-package=""> 扫描该类下所有子包注解配置
public class TestApplicationRun {
    public static void main(String[] args) {
        SpringApplication.run(TestApplicationRun.class, args);
    }
}

4. 基于Java配置

4.1 配置XML引入依赖

<dependency>
            <groupId>com.github.drtrang</groupId>
            <artifactId>druid-spring-boot2-starter</artifactId>
            <version>1.1.10</version>
        </dependency>

4.2 添加jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/数据库名称
jdbc.username=xxxx
jdbc.password=xxxx

4.3 配置数据源

package cn.lingnan.spirngboot.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.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;
import java.util.Date;

@Configuration //声明一个类是一个java配置类,相当于一个xml配置文件
@PropertySource("classpath:jdbc.properties") //读取资源文件
public class JdbcConfiguration {
    @Value("${jdbc.driverClassName}")
    private String driverClassName;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    @Bean//将dataSource注入到Spirng容器中
    public DataSource dataSource() {
        //通常使用this用于区分局部与全局变量
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(this.driverClassName);
        druidDataSource.setUrl(this.url);
        druidDataSource.setUsername(this.username);
        druidDataSource.setPassword(this.password);
        return druidDataSource;
    }
}

4.4 测试

在这里插入图片描述

5.SpringBoot属性注入

5.1 JdbcProperties

package cn.lingnan.spirngboot.config;

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


@ConfigurationProperties(prefix = "jdbc")//声明属性前缀
public class JdbcProperties {
    private String url;
    private String driverClassName;
    private String username;
    private String password;

    public String getUrl() {
        return url;
    }

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

    public String getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    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;
    }
}

5.2 application.properties(配置文件)

SpringBoot会默认读取application.properties的资源文件

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/数据库名称
jdbc.username=xxxx
jdbc.password=xxxx

5.3 JdbcConfiguration(加载)

package cn.lingnan.spirngboot.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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 java.util.Date;

@Configuration //声明一个类是一个java配置类,相当于一个xml配置文件
//@PropertySource("classpath:jdbc.properties") //读取资源文件
@EnableConfigurationProperties(JdbcProperties.class)//启用属性读取类
public class JdbcConfiguration {
    @Autowired
    private JdbcProperties jdbcProperties;

    @Bean//将dataSource注入到Spirng容器中
    public DataSource dataSource() {
        //通常使用this用于区分局部与全局变量
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(this.jdbcProperties.getDriverClassName());
        druidDataSource.setUrl(this.jdbcProperties.getUrl());
        druidDataSource.setUsername(this.jdbcProperties.getUsername());
        druidDataSource.setPassword(this.jdbcProperties.getPassword());
        return druidDataSource;
    }
}

5.4 测试

在这里插入图片描述

6. SpringBoot的自动配置原理

SpringBoot为我们提供了默认配置,而默认配置生效的条件一般有两个:

  • 你引入了相关依赖
  • 你自己没有配置

1)启动器

之所以,我们如果不想配置,只需要引入依赖即可,而依赖版本我们也不用操心,因为只要引入了SpringBoot提供的stater(启动器),就会自动管理依赖及版本了。

因此,玩SpringBoot的第一件事情,就是找启动器,SpringBoot提供了大量的默认启动器,参考课前资料中提供的《SpringBoot启动器.txt》

2)全局配置

另外,SpringBoot的默认配置,都会读取默认属性,而这些属性可以通过自定义application.properties文件来进行覆盖。这样虽然使用的还是默认配置,但是配置中的值改成了我们自定义的。

因此,玩SpringBoot的第二件事情,就是通过application.properties来覆盖默认属性值,形成自定义配置。我们需要知道SpringBoot的默认属性key,非常多,参考课前资料提供的:《SpringBoot全局属性.md》

注:SpringBoot默认只有两个配置文件 1.–application.properties– 2.application.yml

7.整合SpringMVC

7.1 配置pom.xml

<!--所有的SpringBoot应用都要以该工程作为父工程-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

7.2 编写配置文件application.properties

server.port=8888
logging.level.org.springframework=DEBUG//打印更多日志信息

7.3 编写引导类(SpringBoot启动类)

/**
 * 引导类启动
 */
@SpringBootApplication
public class UserApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserApplication.class, args);
    }
}

7.4 编写Controller类

@Controller
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/test")
    @ResponseBody
    public String test() {
        return "hello SpringBoot";
    }
}

7.5 配置拦截器

7.5.1 编写拦截器(MyInterceptor)

@Component
public class MyInterceptor implements HandlerInterceptor {
    /**
     * 前置方法,在Handler方法前执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("前置方法执行");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("后置方法执行");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("完成方法执行");
    }
}

7.5.2 配置拦截器(MyInterceptor)

/**
 * 配置拦截器
 * 1.声明该类是一个java配置类
 * 2.实现WebConfigurer接口
 */
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
    @Autowired
    private MyInterceptor myInterceptor;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //注册拦截器和配置拦截路径
        registry.addInterceptor(myInterceptor).addPathPatterns("/**");

    }
}

8. 整合数据源

8.1 在application.properties中配置

#修改端口号
server.port=8888
#配置日志文件
logging.level.org.springframework=DEBUG
#配置数据源(默认配置是mysql因此driverName可以省略不写)
spring.datasource.url=jdbc:mysql:///数据库名称
spring.datasource.username=xxxx
spring.datasource.password=xxx

8.2 整合Mybatis

8.2.1 配置pom.xml文件

        <!--mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!-- 通用mapper -->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>2.0.2</version>
        </dependency>

8.2.2 配置application.properties

#修改端口号
server.port=8888
#配置日志文件
#logging.level.org.springframework=DEBUG
#配置数据源(默认配置是mysql因此driverName可以省略不写)
spring.datasource.url=jdbc:mysql:///数据库名称
spring.datasource.username=xxxx
spring.datasource.password=xxxx
#配置mybatis信息
mybatis.type-aliases-package=cn.lingnan.user.pojo
# mapper.xml文件位置,如果没有映射文件,请注释掉
# mybatis.mapper-locations=classpath:mappers/*.xml

8.2.3 User实体类

@Table
public class User implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
private String address;

.......

8.2.4 通用Mapper接口

@Mapper
public interface UserMapper extends tk.mybatis.mapper.common.Mapper<User> {
}

8.2.5 UserService

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    /**
     * 根据id查询用户
     * @param id
     * @return
     */
    public User queryUserById(Integer id){
        User user = this.userMapper.selectByPrimaryKey(id);
        return user;
    }

    /**
     * 根据id删除用户信息
     * @param id
     */
    @Transactional //添加事务
    public void deleteUserById(Integer id){
        this.userMapper.deleteByPrimaryKey(id);
    }
}

8.2.6 UserController

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("{id}")
    @ResponseBody
    public User queryUserById(@PathVariable("id")Integer id){
        return userService.queryUserById(id);
    }

    @RequestMapping("/test")
    @ResponseBody
    public String test() {
        return "hello SpringBoot";
    }
}

9. 总结

① SpringBoot的四种属性注入@Autowired注入
② 构造方法注入
③ @Bean方法形参注入
④ 直接在@Bean方法上使用@ConfigurationProperties(prefix = “jdbc”)

相对重要的注解:
@SpringBootApplication
@Configuration
@Bean
@ConigurationProperties
@EnableConfigurationProperties

1.什么是SpringBoot?
搭建Spring应用的脚手架,内置tomcat。打成jar,自动配置(根据引入的依赖)
2.Java配置
(1)原生的java配置

① @Configuration
② @Bean:把方法的返回值注入到Spring容器
③ @Value:
④ @PropertySource

(2)SpringBoot提供能Java配置

①@ConfigurationProperties(prefix = “Jdbc”):声明一个类是一个属性读取类读取application.properties/yml
②@EnableConigurationProperties(属性读取类.class)
-----1)@Autowired注入
-----2)构造方法注入
-----3)通过@Bean方法参数注入
-----4)直接在@Bean方法上使用@ConfigurationProperties(prefix = “jdbc”)

3.SpringBoot的基本使用
(1)搭建SpringBoot的基本应用

①引入统一的父工程,以及需要的启动器
②覆盖默认配置
③添加引导类:@SpringBootApplication(@EnableAutoConfiguration @ComponentScan @SpringBoogConfiguration)

(2)整合SpringMVC

①修改端口(server.port=xxxx)

②访问静态资源(classpath:META/resourves classpath:resources classpath:public)

③拦截器:
1)自定义拦截器:实现HandlerInterceptor接口
2)配置拦截器:自定义一个java配置类(@Configuration),实现WebMvcConfigurer接口

④整合数据源
1)引入jdbc启动器(内置hikariCP) mysql驱动
2)添加配置:spring.dataSource.url username password

⑤整合mybatis
1)引入启动器
2)覆盖默认配置:mybatis.type-aliases-package=cn.lingnan.pojo mybatis.mapper-location=classpath:mybatis/mappers/**/*.xml
3)代码:定义一个接口,在接口上添加@Mapper注解

⑥整合通用mapper:
1)引入启动器
2)代码:接口继承Mapper

⑦整合事务:添加@Transactional

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值