栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

动力节点springboot笔记

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

动力节点springboot笔记

1、入门 1.1、springboot的特性
  • 能够快速创建基于spring的应用程序
  • 能够直接使用java main方法启动内嵌的tomcat服务器运行springboot程序,不需要部署war包文件
  • 提供约定的starter POM来简化Maven配置,让Maven的配置变的简单
  • 自动化配置,根据项目的Maven依赖配置,springboot自动配置Spring,Spring mvc等
  • 提供了程序的健康检查等功能
  • 基本可以完全不使用XML配置文件,采用注解配置
1.2、springboot四大核心
  • 自动配置
  • 起步依赖
  • Actuator
  • 命令行界面
2.集成springmvc

创建好springboot项目就代表了已经创建好了springmvc项目,因为springboot框架已经帮助我们自动配置了springmvc,之后按照springmvc的代码书写规范就可以进行书写了

注:创建包的时候一定要创建在application类的同级包下

IndexController类

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

@Controller
public class IndexController {

    @RequestMapping(value = "/springboot/say")
    //加上这个注解相当于就是不走视图解析器 直接返回一个json格式的对象
    @ResponseBody
    public String say(){
        return "hello springboot";
    }
}

启动项目的方式就是直接运行applicaiton中的main方法

3、核心配置文件

注:核心配置文件在一个项目中只能有一个

3.1、application.properties配置文件
#设置端口号
server.port=8081
#设置项目地址根 必须以斜杠开头 此时所有的请求前都要加上springboot
server.servlet.context-path=/springboot
3.2、yml和yaml配置文件

使用springboot核心配置文件application.yml或者application.yaml

server:
  # 注意后面要加空额
  port: 8081
  servlet:
    context-path: /

两种配置文件本质上是一样的,写法也是一模一样的只是后缀不同

3.3、核心配置文件同时存在的情况

配置文件优先级顺序 properties > yml > yaml

3.4、多环境下的核心配置文件

工作中的环境:开发环境,测试环境,生产环境,准生产环境

首先我们在resources目录中创建多个配置文件表示不同的生产环境

application-dev.properties表示开发环境

#开发环境配置文件
server.port=8080
server.servlet.context-path=/dev

application-test.properties表示测试环境

#测试环境
server.port=8081
server.servlet.context-path=/test

application-ready.properties表示准生产环境

#准生产环境
server.port=8082
server.servlet.context-path=/ready

application-product.properties表示生产环境

#生产环境
server.port=9090
server.servlet.context-path=/product

我们需要在主配置文件中选择当前激活哪一个配置文件

#注核心配置文件
#激活使用的配置文件 填写的是-后面的名字
spring.profiles.active=test

如果我们使用yml或者yaml配置文件来配置多环境,写法与properties的关键字一样,写法就是yml的写法

3.5、自定义配置

首先我们在application.properties中自定义几个属性

#设置端口号
server.port=8080
#设置地址前缀
server.servlet.context-path=/

#自定义属性
school.name=hty
websit=http://www.autunomy.top

在controller程序中我们使用@Value注解来提取

package com.hty.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class IndexController {
    //使用value注解可以读取自定义属性
    @Value("${school.name}")
    private String schoolName;

    @Value("${websit}")
    private String websit;

    @RequestMapping(value="/say")
    @ResponseBody
    public String say(){
        return "hello:"+schoolName+":"+websit;
    }
}
3.6、自定义配置映射为对象

首先我们在application.properties中创建一些自定义配置

server.port=8080
server.servlet.context-path=/


school.name=hty
school.websit=http://www.autunomy.top


abc.name=abc
abc.websit=http://www.abc.com

之后我们创建一个配置类

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

@Component//将该类交给spring容器进行管理
@ConfigurationProperties(prefix = "school")//必须有前缀,前缀就是自定义配置的前缀
public class School {
    private String name;
    private String websit;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getWebsit() {
        return websit;
    }

    public void setWebsit(String websit) {
        this.websit = websit;
    }
}

使用这两个注解就可以让sprin容器进行管理

然后我们进行测试

package com.hty.controller;

import com.hty.config.School;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class IndexController {
	
    //由于已经交给spring容器进行管理,所以我们可以使用自动装配
    @Autowired
    private School school;

    @RequestMapping("/say")
    @ResponseBody
    public String say(){
        return "学校名称"+school.getName()+" "+"学校网站"+school.getWebsit();
    }
}

当我们写完配置类的时候,会出现警告,解决方法就是添加依赖


    org.springframework.boot
    spring-boot-configuration-processor
    true

4、springboot集成jsp

环境搭建:首先创建一个springboot的项目,然后在main下面创建一个webapp文件夹,之后点开项目结构

将webapp目录添加进去,然后点击create artifacts 然后点击apply然后ok

还需要添加依赖



    org.apache.tomcat.embed
    tomcat-embed-jasper

还需要在pom文件中的build标签下进行配置



    
        
        src/main/webapp
        
        META-INF/resources
        
        
            
            *.*
        
    
    
        src/main/java
        
            ***.dtd
        
        false
    
    
        src/main/resources
        
            ***.properties
        
        false
    

最后一步就是在application.properties中配置视图解析器

#配置视图解析器
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp

现在开始编写controller然后创建jsp之后测试,步骤就和springmvc中的步骤一模一样

5、springboot集成mybatis

首先添加依赖



    mysql
    mysql-connector-java



    org.mybatis.spring.boot
    mybatis-spring-boot-starter
    2.2.2

5.1mybatis逆向工程

使用mybatis提供的逆向工程生成实体bean,映射文件,DAO接口

首先搭建数据库

drop table if exists t_student;
create table t_student
(
   id                   int(10)                        not null auto_increment,
   name                 varchar(20)                    null,
   age                  int(10)                        null,
   constraint PK_T_STUDENT primary key clustered (id)
);

insert into t_student(name,age) values("zhangsan",25);
insert into t_student(name,age) values("lisi",28);
insert into t_student(name,age) values("wangwu",23);
insert into t_student(name,age) values("Tom",21);
insert into t_student(name,age) values("Jck",55);
insert into t_student(name,age) values("Lucy",27);
insert into t_student(name,age) values("zhaoliu",75);

创建GeneratorMapper.xml配置文件在工程的根目录,要注意对其中的一些配置进行更改,改为自己的配置





    
    

    
    
        
        
            
        


        
        
        
        
        
            
            
        

        
        
            
        

        
        
            
        

        
        

导入插件



    org.mybatis.generator
    mybatis-generator-maven-plugin
    1.3.6
    
        
        GeneratorMapper.xml
        true
        true
    

完成配置之后我们打开maven管理、点击plugins,点击

然后就可以自动生成了

5.2、mapper.xml

首先观察了mapper接口,我们会发现总共会有6个方法但是其中插入和更新是有两个方法,再根据mapper.xml文件中sql语句的样式来看,其中的一个插入和更新的方法是使用动态sql来进行更改数据库的,就是我们可以不传递完全部的数据库字段,只需要传递一部分就可以实现这个功能,另一个插入和更新就是普通的方法,需要传递所有的参数

注:mybatis的逆向工程只会针对单表操作

5.3、集成mybatis

由于dao层已经由mybatis逆向工程生成了,所以我们主需要写service层和controller层,但是由于service层需要调用dao层,但是spring容器中并没有mapper的实例,所以我们需要在mapper文件中加入一个注解

package com.hty.mapper;

import com.hty.pojo.Student;
import org.apache.ibatis.annotations.Mapper;

@Mapper//扫描DAO接口到spring容器中
public interface StudentMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(Student record);

    int insertSelective(Student record);

    Student selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Student record);

    int updateByPrimaryKey(Student record);
}

这个注解用来扫描DAO中的接口,spring容器就会管理这些接口

之后由于controller层需要调用service层,所以也需要让spring容器去管理service层的文件

注:service注解需要加在实现类上,因为spring只能管理类,不能管理接口

package com.hty.service;

import com.hty.mapper.StudentMapper;
import com.hty.pojo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class StudentServiceImpl implements StudentService{
    @Autowired
    private StudentMapper studentMapper;
    public void setStudentMapper(StudentMapper studentMapper) {
        this.studentMapper = studentMapper;
    }

    @Override
    public Student queryStudentById(Integer id) {
        return studentMapper.selectByPrimaryKey(id);
    }
}

之后我们还需要在application.properties中配置数据库连接的相关属性

#配置连接数据库的配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456

之后启动项目就可以访问了

5.4、MapperScan注解的位置

由于我们的mapper文件会有多个,每一个都要加上@Mapper很麻烦,所以我们可以在application启动入口类上加上@MapperScan,mapper类就不需要加@Mapper注解

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

@SpringBootApplication
@MapperScan(basePackages = "com.hty.mapper")//指定要扫描的包
public class Application {

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

}
5.5、mapper.xml文件的位置

我们还有一个地方可以存放mapper.xml文件,就是在resources路径下的mapper目录,在这里存放mapper文件那就需要在application.properties中进行配置

mybatis.mapper-locations=classpath:mapper
        //获取springboot容器
        ConfigurableApplicationContext run = SpringApplication.run(Application.class, args);

        //从spring容器中获取指定bean对象
        StudentService studentService = (StudentService)run.getBean("studentServiceImpl");

        //调用方法
        System.out.println(studentService.sayHello());
    }

}

最后就会输出 say Hello

10.2、方法二

实现CommandLineRunner接口,重写run方法

service类和前一个例子一样

import com.hty.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application implements CommandLineRunner {

    //3.注入这个类
    @Autowired
    private StudentService studentService;

    public static void main(String[] args) {
        //1.Springboot启动程序会初始化Spring的容器
        SpringApplication.run(Application.class, args);
    }

    //2.重写CommandLineRunner类中的run方法
    @Override
    public void run(String... args) throws Exception {
        //4.调用业务方法
        System.out.println(studentService.sayHello("world"));
    }
}
转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号