SpringBoot初级入门

10 篇文章 0 订阅

SpringBoot

用一些固定的方式来构建生产级别的Sping应用。推崇约定大于配置的方式(不需要配置),便于能够尽可能快速的启动并运行程序。
SpringBoot称为搭建程序的脚手架。
作用:快速构建庞大的Spring项目,并尽可能的减少一切xml配置。

1.了解

1.1为什么学习SpringBoot

  • 复杂配置
  • 混乱的依赖管理
    SpringBoot让这一切成为过去,简化了基于Spring的应用开发,只需要“run”就能创建一个独立的、生产级别的Spring应用。
    Spring Boot为Spring平台及第三方库提供开箱即用的设置(提供默认配置,这些配置在启动器starter中)。

1.2特点

  • 为所有Sping的开发者提供一个快速的、广泛接受的入门体验。
  • 开箱即用。启动器starter其实就是SpingBoot提供的一个jar包,但通过自己设置参数.properties。
  • 提供一些大型项目中常见的非功能性特性。

2.入门

在这里插入图片描述

2.1想要SpringBoot帮你构建,就必须使用SpringBoot作为你的父工程,就需要配置pom.xml,如下:

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
    </parent>
  

在这里插入图片描述

2.2此时想要搭建一个SpringMVC的web程序,需要在pom.xml中添加依赖。

 <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
添加一个启动器,这个启动器就是Spring提供的一个Web工程的启动器,并且不用写版本号。
引入启动器只需要引入这个启动器的名字,版本由上面的父工程来管理。

在这里插入图片描述
该图可看到需要引入的jar包都已经被下下来了。

2.3新建包、类,main方法(注意加注解@SpringBootApplication

package cn.itcast;

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

@SpringBootApplication
public class BootDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(BootDemoApplication.class,args);
    }
}
其中@SpringBootApplication注解:
是Sprnig Boot项目的核心注解,目的是开启自动配置。
可参考理解:https://blog.csdn.net/u013473691/article/details/52353923

此时运行会失败,因为没有Controller,需要再写一个Controller

2.4编写Controller启动测试

test1

package cn.itcast.web;

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

@Controller
public class HelloController {

    @GetMapping("hello")
    @ResponseBody
    public String hello(){
        return "hello,spring boot!!";
    }
}
@getMapping = @requestMapping(method = RequestMethod.GET)。

test2

@RestController
public class HelloController {

    @GetMapping("hello")
    public String hello(){
        return "hello,spring boot!!";
    }
}
@RestController = @ResponseBody + @Controller
Spring4之后新加入的注解。

2.5 为什么没有web.xml也可以运行

servlet3.0以后可以不用web.xml配置了。
对于不使用springboot的项目,想要不使用web.xml,需要在pom.xml中添加如下,最重要的是plugin中内容:

<!-- 告诉maven,我真的不需要web.xml -->
<plugin>  
    <groupId>org.apache.maven.plugins</groupId>  
    <artifactId>maven-war-plugin</artifactId>  
    <version>2.6</version>  
    <configuration>  
        <failOnMissingWebXml>false</failOnMissingWebXml>  
    </configuration>  
</plugin> 

<properties>
        <!-- 文件拷贝时的编码 -->  
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>  
        <!-- 编译时的编码 -->  
        <maven.compiler.encoding>UTF-8</maven.compiler.encoding>  
        <!-- jdk编译版本 -->
        <java.version>1.7</java.version>
        <!-- 代表项目不需要web.xml -->
        <failOnMissingWebXml>false</failOnMissingWebXml>
  </properties>

此时再运行就可以成功访问了。

3.Java配置

在入门实例中,没有任何配置,就可以实现一个SpringMVC的项目。
但是SpringBoot不可能全部帮你配置好,只能配置最基本的。
Spring3.0及以后:
推荐使用完全的java配置来替代以前的xml。

3.1尝试Java配置

java配置主要靠java类和一些注解,比较常用的注解:

  • @Configuration:声明一个类作为配置类,代替xml方法。
  • @Bean:声明在方法上,将方法的返回值加入Bean,代替<bean标签。
  • @Value:属性注入。
  • @PropertySource:指定外部属性文件,。

以配置数据库连接池为例:
Spring2.0配置:

<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">   
    <property name="url" value="${jdbc_url}" />  
    <property name="username" value="${jdbc_user}" />  
    <property name="password" value="${jdbc_password}" />  
</bean>
3.1.1引入Druid连接池依赖
<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.6</version>
        </dependency>

3.1.2新建jdbc.properties文件

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/xxx?useSSL=false&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456

3.1.3编写配置类

package cn.itcast.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;

@Configuration
@PropertySource("classpath:jdbc.properties")
public class JdbcConfig {
    @Value("${jdbc.driverClassName}")
    String driverClassName;
    @Value("${jdbc.url}")
    String url;
    @Value("${jdbc.username}")
    String username;
    @Value("${jdbc.password}")
    String password;
//    方法的返回值就是要配置的对象
    @Bean
    public DataSource dataSource(){
        DruidDataSource dateSource = new DruidDataSource();
        dateSource.setDriverClassName(driverClassName);
        dateSource.setUrl(url);
        dateSource.setUsername(username);
        dateSource.setPassword(password);
        return dateSource;
    }
}

3.1.4测试是否配置成功

在HelloController中注入DataSource,使用debug检查DataSource的属性是否注入数据。

import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;

@RestController
public class HelloController {

//在JdbcConfig配置类中已经通过@Bean配置方法使得DateSource作为一个类去使用,所以此处可以用作类来注入。
    @Autowired
    private DataSource dateSource;

    @GetMapping("hello")
    public String hello(){
        return "hello,spring boot!!";
    }
}

以上方式太繁杂,所以可以用以下方式自动配置

4.SpringBoot属性注入

还是以jdbc配置为例。

4.1方式一

4.1.1新建配置文件application.properties(默认文件名)

之后所有的配置都可以写来这里面,以key—value对方式存在。

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/xxx?useSSL=false&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456
4.1.2添加lombok依赖

一个编译时的依赖,作用是用@Data注解,里面自动带有setter、getter、构造方法等。

<dependency>
     <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
</dependency>
4.1.3新建JDBC属性类,为属性赋值

这个类的作用是去读application.properties中对应的属性,并将这些属性变成一个类的属性。

package cn.itcast.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "jdbc")
@Data
public class JdbcProperties {
    String driverClassName;
    String url;
    String username;
    String password;
}
其中@ConfigurationProperties要搭配@EnableConfigurationProperties(@ConfigurationProperties所配置的类名.class)来使用。
@ConfigurationProperties(prefix = "jdbc")是根据application.properties中属性实际是jdbc.属性名,但是该类的属性却没有钱的jdbc,所以需要再注解中注明前缀。
4.1.4新建配置类,注入属性

该类的作用是启动配置属性,可以引入属性类,使用属性类。

@Configuration
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfig {
    @Bean
    public DataSource dataSource(JdbcProperties prop){
        DruidDataSource dateSource = new DruidDataSource();
       dateSource.setDriverClassName(prop.driverClassName);
        dateSource.setUrl(prop.url);
        dateSource.setUsername(prop.username);
        dateSource.setPassword(prop.password);
        return dateSource;
    }
}
一旦加上@EnableConfigurationProperties注解,可以在这个类中使用@Autowired注入,也可以使用构造函数方式注入:
@Autowired
JdbcProperties jdbcProperties;

public JdbcConfig(JdbcProperties jd){
	this.jdbcProperties = jdbcProperties;
}

该方法适用于很多地方都需要用到属性类的情况。

4.2方式二

该方法适合只使用一次的。

4.2.1新建配置文件application.properties(默认文件名)

之后所有的配置都可以写来这里面,以key—value对方式存在。

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/xxx?useSSL=false&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456
4.2.2 新建注入属性类JdbcConfig
 @Configuration
    public class JdbcConfig {
        @Bean
        @ConfigurationProperties(prefix = "jdbc")
        public DataSource dataSource(){
            return new DruidDataSource();
        }
    }

5.配置文件

配置文件除了可以使用application.properties类型,还可以使用后缀名为:yml或者yaml的类型,也就是application.yml或application.yaml。
以jdbc为例,基本格式为:(也可以配置对象,集合,例user、language)

jdbc:
  driverClassName: com.mysql.jdbc.Driver
  url: jdbc:mysql://localhost/jfweb?useSSL=false&useUnicode=true&characterEncoding=utf8
  username: root
  password: 123456
  user: 
  	name: jack
  	age: 21
  	language:
  		-java
  		-php
  		-ios

注意:
如果application.properties和application.yaml两个配置都有,其配置内容则取∪并集,若两个配置文件存在冲突,则取application.properties。

6.自动配置原理

6.1注解

  • @SpringBootApplication = @Configuration声明是一个配置类
    加了@SpringBootApplication 的类就是一个配置类,就可以在里面加任何配置。
  • @EnableAutoConfiguration开启自动配置
    监测,看你引入什么依赖,他就猜测需要什么配置,就会自动配置。
  • @ComponentScan扫描包
    没有指定的话,会从开始声明注解所在的包开始扫描。
  • @ConditionalOnWebApplication(type = TYPE.SERVLET)
    满足参数中的条件,这个类作为配置类才起作用。
  • @ConditionalOnClass({Servlet.class,DispatherServlet.class,WebMvcConfigurer.class})
    满足参数中的条件,要有有这三个类。
  • @ConditionalOnMissingBean
    对于该注解标注的方法,若我们自己配置的就,那么该方法就不生效,否则默认使用该方法。即自定义的机会。
    通过注解去判断。

总结

SpringBoot的默认配置生效的条件一般有两个:

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

6.2总结

(1)启动器
若我们不想配置,只需要引入依赖即可,而依赖版本我们也不用操心,因为只要引入SpringBoot提供的starter,就会自动管理依赖及版本。启动器引入依赖都是spring-boot-starter-xxx
(2)全局配置
SpringBoot的默认配置都会读取默认属性,而这些属性可以通过自定义application.properties文件来覆盖,这样虽然使用的还是默认配置,但是配置中的值改成了我们自定义的。

7.yaml文件中其他配置

访问端口号:

server:
  port: 8088

过滤器,url拦截路径,即访问映射路径,
默认是/,拦截所有

server:
  servlet:
    context-path: "*.do"
@RestController
public class HelloController {
    @GetMapping("hello.do")
    public String hello(){
        return "hello,spring boot!!";
    }

http://localhost:8088/hello.do访问成功
日志级别:level的值是key-value
可以控制日志级别,控制资质精细度。

logging:
  level: 
    cn.itcast: debug
    org.springframwork: debug

8.静态资源

查看源码,默认配置的静态资源路径:
在这里插入图片描述
在src/main/resources新建static包
在static包里可以存放图片等。
例:
http://localhost:8088/heads.png
但是在前后端分离开发中,前端由前端控制,后端不管前端,对于纯粹的前后端分离开发中,这种方式用不到,因为后端只提供java代码,只提供接口。

9.拦截器

拦截器不是一个普通属性,而是一个类,所以就要用到java配置方式了。
注:
如果想要保持SpringBoot的一些默认MVC特性,同时又想自定义一些MVC配置。应该让一个类实现WebMvcConfigurer,冰鞋添加@Configuration
如果想要完全自动自定义SpringMVC,不保留SpringBoot提供的一切特征,可以自己定义类并添加@Configuration和@EnableWebMvc。

9.1自定义拦截器

public class LoginInterceptor implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        logger.debug("preHandle method is now running!");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        logger.debug("postHandle method is now running!");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        logger.debug("afterCompletion method is now running!");
    }
}

9.2定义配置类,注册拦截器

@Configuration
public class MvcConfig implements WebMvcConfigurer{
    /**
     * 通过@Bean注解,将我们定义的拦截器注册到Spring容器
     * @return
     */
    @Bean
    public LoginInterceptor loginInterceptor(){
        return new LoginInterceptor();
    }

    /**
     * 重写接口中的addInterceptors方法,添加自定义拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 通过registry来注册拦截器,通过addPathPatterns来添加拦截路径
        registry.addInterceptor(this.loginInterceptor()).addPathPatterns("/**");
    }
}

10.整合jdbc

10.1引入依赖添加配置

引入连接池依赖:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

已经默认支持:
在这里插入图片描述
添加mysql驱动依赖:

 <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

修改配置文件

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost/yum6
    username: root
    password: 123456

11.整合mybatis

11.1.引入依赖

引入mybatis的启动器

<dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>

11.2添加配置

mybatis:
  configuration:
    #驼峰命名
    map-underscore-to-camel-case: true
  #mapper-locations: mapper/*.xml 
  type-aliases-package: cn.itcast.pojo

11.3配置映射文件

由于yaml文件中无法配置映射文件路径,所以用注解@MapperScan类配置

@SpringBootApplication
@MapperScan("cn.itcast.mapper")
public class BootDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(BootDemoApplication.class,args);
    }
}

11.4通用mybatis

适用与单表增删改查

11.4.1引入依赖
<!--通用mapper-->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>2.0.3</version>
        </dependency>
11.4.2使用
package cn.itcast.config.mapper;

import cn.itcast.pojo.User;
import tk.mybatis.mapper.common.Mapper;

public interface UserMapper extends Mapper<User> {
}
11.4.3不需要的依赖和配置删掉

由于通用mapper的jar包中含有jdbc和mysql依赖,所以不需要之前引入的jdbc和mysql(重复)。
通用mapper中已经开启驼峰命名,所以yaml文件中也不需要了这个配置了。

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.6</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
        <!--通用mapper-->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>2.0.3</version>
        </dependency>
    </dependencies>

logging:
  level:
    cn.itcast: debug
    org.springframwork: debug
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost/yum6
    username: root
    password: 123456
mybatis:
 # configuration:
    #驼峰命名
#    map-underscore-to-camel-case: true
  #mapper-locations: mapper/#.xml
  type-aliases-package: cn.itcast.pojo

@MapperScan(“cn.itcast.mapper”)注解类改为import tk.mybatis.spring.annotation.MapperScan;

package cn.itcast;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;

@SpringBootApplication
@MapperScan("cn.itcast.mapper")
public class BootDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(BootDemoApplication.class,args);
    }
}
11.4.4映射类和表名

@Table(“表名”):映射类和表名
@Id:被标注的属性是表的主键
@KeySql(useGeneratedKeys = true):表示主键递增
@Transient:被标注的属性并非一个到数据库表的字段的映射,ORM框架将忽略该属性

package cn.itcast.pojo;

import lombok.Data;
import tk.mybatis.mapper.annotation.KeySql;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.Date;

@Data
@Table(name="tb_user")
public class User {
    //id
    @Id
    @KeySql(useGeneratedKeys = true)
    private Long id;
    //用户名
//    @Column(name = "username")
    private String username;
    //密码
    private String password;
//    @Transient
//    private String note;
      private String phone;
      private Date created;

}
注意:
使用通用mapper时,实体类属性名中有大写字母的对应数据库中字段就有分隔符“_”,例如,userName对应user_name,此时可以使用 @Column(name = "username")注解来注明该属性在数据库中字段名。
11.4.5测试类

引入依赖:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

编写Mapper

package cn.itcast.mapper;

import cn.itcast.pojo.User;
import tk.mybatis.mapper.common.Mapper;

public interface UserMapper extends Mapper<User> {
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
    @Autowired
    private UserMapper userMapper;
    @Test
    public void test(){
        User user = userMapper.selectByPrimaryKey(16);
        System.out.println(user);
    }
}
@RunWith
JUnit为项目每个类都创建一个对应的测试类,虽然一次能把类里面所有方法都测试一遍,但是一个项目有上百个类,总不能每个类都点一下进行测试。
@RunWith就是为了这种情况,我们先声明用套件运行器进行测试,然后把需要进行测试的所有类放进套件(集合)里,一次就可以把所有类所有方法测试完,也叫打包测试。让测试云星宇Spring测试环境。
11.4.6web测试

service类

package cn.itcast.service;

import cn.itcast.mapper.UserMapper;
import cn.itcast.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

    public User queryById(Long id){
        return userMapper.selectByPrimaryKey(id);
    }
    //事务注解,表示该方法需要事务
    @Transactional
    public void insertUser(User user){
        userMapper.insert(user);
    }
}

controller类

package cn.itcast.web;

import cn.itcast.mapper.UserMapper;
import cn.itcast.pojo.User;
import cn.itcast.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("user")
public class TestController {
    @Autowired
    private UserService userService;
    @GetMapping("{id}")
    public User userTest(@PathVariable("id") Long id){
        return userService.queryById(id);
    }
}

访问:http://localhost:8080/user/16
在这里插入图片描述
访问成功!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值