【SpringBoot框架】-- 快速入门

目录

1. spring简介

1.1 springboot快速入门

1.1.1 开发步骤

1.1.2 创建项目

2. springboot的特点

3. 配置文件种类

4. 读取配置文件中的内容

4.1 @ConfigurationPropertie

4.2  @Value

5. profile多环境配置 

6. springboot注册web组件

7. springboot包扫描的原理

8. springboot的自动装配原理【了解】

9. springboot整合mybatis


1. spring简介

Spring框架是一个开源的Java应用框架,以其轻量级、非侵入性、控制反转和依赖注入、面向切面编程等特性著称。它简化了Java应用开发,提供了强大的基础设施支持和丰富的功能集合,使开发者能够更专注于业务逻辑的实现,从而提升了开发效率和代码质量。

1.1 springboot快速入门

1.1.1 开发步骤

SpringBoot 开发起来特别简单,分为如下几步:

  • 创建新模块,选择Spring初始化,并配置模块相关基础信息
  • 选择当前模块需要使用的技术集
  • 开发控制器类
  • 运行自动生成的Application类

1.1.2 创建项目

这里选择了JDK17,因为Spring Boot 3 要求使用 Java 17 或更高版本,因为 Java 17 引入了许多新特性和性能改进,同时也提供了更好的语言特性支持。

注意:打包方式这里需要设置为 Jar

  • 接下来选择springboot的版本,我们这里选择3.0版本的,
  • 选中 Web,然后勾选 Spring Web

  • 点击创建,完成

  • 结构列表如下

 

注意:

  1. 在创建好的工程中不需要创建配置类

  2. 创建好的项目会自动生成其他的一些文件,而这些文件目前对我们来说没有任何作用,所以可以将这些文件忽略。

    可以忽略的目录和文件如下:

    • .mvn
    • .gitignore
    • HELP.md
    • mvnw
    • mvnw.cmd

2. springboot的特点

1) 自动配置

Spring Boot的自动配置是一个运行时(更准确地说,是应用程序启动时)的过程,考虑了众多因素,才决定Spring配置应该用哪个,不该用哪个。该过程是SpringBoot自动完成的。

2) 起步依赖

起步依赖本质上是一个Maven项目对象模型(Project Object Model,POM),定义了对其他库的传递依赖,这些东西加在一起即支持某项功能。

简单的说,起步依赖就是将具备某种功能的坐标打包到一起,并提供一些默认的功能。

3) 辅助功能

提供了一些大型项目中常见的非功能性特性,如嵌入式服务器tomcat、安全、指标,健康检测、外部配置等。

3. 配置文件种类

application.propertiesapplication.yml(或 application.yaml)是 Spring Boot 应用程序中最常用的两种配置文件格式。以下是对它们的详细介绍:

application.properties

  • 格式:这是一个基于键值对的配置文件,每行包含一个键值对,键和值之间用等号(=)分隔。

  • 注释:以 # 开头的行被视为注释,Spring Boot 会忽略这些行。

  • 示例

    # Database configuration 
    spring.datasource.driverclassname=com.mysql.cj.jdbc.Driver
    spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=dbuser 
    spring.datasource.password=dbpass

application.yml 或 application.yaml

  • 格式:YAML 是一种更易于阅读的数据序列化格式,它使用缩进来表示层级结构,而不是像 properties 文件那样使用等号分隔键值对。

  • 注释:以 # 开头的行也是注释。

  • 结构化:YAML 允许你以结构化的方式组织配置,例如使用列表和映射(类似于 JSON 对象)。

  • 示例

    # Database configuration 
    spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver 
    url: jdbc:mysql://localhost:3306/student 
    username: root 
    password: 123456
    

选择哪种格式?

  • 简洁性:如果你的配置相对简单,properties 文件可能更简洁。

  • 复杂性:对于复杂的配置,YAML 提供的结构化能力可能更有优势。

  • 可读性YAML 通常被认为更易于阅读和编写,特别是对于具有嵌套结构的配置。

  • 工具支持:某些编辑器和 IDE 对 YAML 格式有更好的支持,包括语法高亮和格式化。

配置文件的加载顺序

Spring Boot 在启动时会按照一定的顺序加载配置文件:

  1. application.propertiesapplication.yml(默认配置文件)

  2. 激活的 profile 特定的配置文件,如 application-dev.propertiesapplication-dev.yml

  3. 命令行参数

  4. 来自环境变量的配置

4. 读取配置文件中的内容

springboot提供了两种方式用于读取springboot配置文件中信息的方式。

4.1 @ConfigurationPropertie

使用在类上 @ConfigurationProperties(prefix="前缀")

4.2  @Value

@Value 注解可以用来将配置文件中的值注入到Spring管理的Bean的字段中,但是它只能读取基本类型和字符串类型。

5. profile多环境配置 

我们在开发Spring Boot应用时,通常同一套程序会被安装到不同环境,比如:开发、测试、生产等。其中数据库地址、服务器端口等等配置都不同,如果每次打包时,都要修改配置文件,那么非常麻烦。profile功能就是来进行动态配置切换的。

1) profile配置方式

  • 多profile文件方式

  • yml多文档方式

2) profile激活方式

  • 配置文件

  • 命令行参数

我们需要针对不同的环境来创建不同的配置文件。使用profile来激活对应的配置文件

比如:

application-dev.properties [开发环境的配置文件] application-test.properties [测试环境的配置文件] application-pro.properties [生产环境的配置文件] 相同配置依然还是放在application.properties中

如何激活对于的配置文件。激活的方式有两种:

第一种: 之间在application配置文件中

#激活对应环境的配置文件

spring.profiles.active=pro

第二种: 部署时如何激活对应环境的配置

命令行参数:java –jar xxx.jar --spring.profiles.active=dev

6. springboot注册web组件

创建一个Servlet

public class MyServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
    }
}

创建一个配置类

@Configuration //表示该类为配置类,等价于之前的xml配置文件
public class MyConfig {
​
    @Bean //等价于<bean标签.
    public ServletRegistrationBean  myServlet(){
        ServletRegistrationBean bean=new ServletRegistrationBean();
        bean.setServlet(new MyServlet());
        bean.setName("my");
        bean.setLoadOnStartup(1);
        bean.addUrlMappings("/my");
        return bean;
    }
}
​

7. springboot包扫描的原理

ssm项目必须加包扫描。而现在springboot没有在写包扫描了。自带了包扫描的功能。核心在主类上@SpringBootApplication上,它是一个复合注解。里面包含@EnableAutoConfiguration开启自动配置,里面包含@AutoConfigurationPackage。@Import({AutoConfigurationPackages.Registrar.class})需要导入一个自动配置包的类。加载主类所在的包,并按照该包进行扫描。

我们如果不想让他扫描主类所在的包,我们可以使用@CompentScan(basePackages={})来指定自己的包

8. springboot的自动装配原理【了解】

我们原来ssm项目,都需要加载前端控制器DispatcherServlet. 而现在的springboot并没有加载DispatcherServlet。 springboot具备自动装配的功能。

springboot启动时,加载了使用@SpringbootApplication注解的类,该注解是一个符合注解,包含@EnableAutoConfiguration该注解开启了自动装配功能,该注解也是一个符合注解里面包含@Import({AutoConfigurationImportSelector.class}),导入AutoConfigurationImportSelector该类自动装配选择器类,该类会自动加载很多自动装配。每个自动装配会完成对于的自动装配功能

9. springboot整合mybatis

引入依赖

 <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>3.0.3</version>
        </dependency>

        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter-test</artifactId>
            <version>3.0.3</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

配置文件

server:
  port: 8080

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

mybatis:
  mapper-locations: classpath:mapper/*.xml

实体类

@Data
public class User implements Serializable {
    /**
     * 
     */
    private Integer id;

    /**
     * 
     */
    private String username;

    /**
     * 
     */
    private String password;

    /**
     * 
     */
    private String phone;

    private static final long serialVersionUID = 1L;
}

dao

public interface UserMapper {

    User selectById(Integer id);

    List<User> selectAll();

    int deleteById(Integer id);

    int add(User user);

    int update(User user);
}

映射文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ljf.dao.UserMapper">


    <select id="selectById" resultType="com.ljf.domain.User" parameterType="java.lang.Integer">
        select * from user where id=#{id}
    </select>

    <select id="selectAll" resultType="com.ljf.domain.User" >
        select * from user
    </select>

    <update id="update">
        update user
        <set>
            <if test="username != null">username = #{username},</if>
            <if test="password != null">password = #{password},</if>
            <if test="phone != null">phone = #{phone},</if>
        </set>
        where id = #{id}
    </update>

    <delete id="deleteById" >
        delete from user where id=#{id}
    </delete>
    
    <insert id="add">
        insert into user(username, password, phone) values(#{username},#{password},#{phone})
    </insert>
</mapper>

service

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public R selectById(Integer id) {
        User user = userMapper.selectById(id);
        if (user == null){
            return new R(500,"查询失败",null);
        }else {
            return new R(200,"查询成功",user);
        }

    }

    @Override
    public R selectAll() {
        List<User> users = userMapper.selectAll();
        return new R(200,"查询成功",users);
    }

    @Override
    public R deleteById(Integer id) {
       int i = userMapper.deleteById(id);
       if (i>0){
           return new R(200,"查询成功",null);
       }
       return new R(500,"查询失败",null);
    }

    @Override
    public R add(User user) {
        int i = userMapper.add(user);
        if (i>0){
            return new R(200,"查询成功",null);
        }
        return new R(500,"查询失败",null);
    }

    @Override
    public R update(User user) {
        int i = userMapper.update(user);
        if (i>0){
            return new R(200,"查询成功",null);
        }
        return new R(500,"查询失败",null);
    }
}

controller代码

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public R list(){
        return userService.selectAll();
    }

    @GetMapping("/getById")
    public R getById(Integer id){
        return userService.selectById(id);
    }

    @DeleteMapping("/deleteById")
    public R deleteById(Integer id){
        return userService.deleteById(id);
    }

    @PostMapping("/add")
    public R add(@RequestBody User user){
        return userService.add(user);
    }

    @PutMapping("/update")
    public R update(@RequestBody User user){
        return userService.update(user);
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值