Springboot初体验(一)

Spring Boot是简化Spring应用初始化和开发的框架,它整合了多种框架和库,支持快速构建独立应用,内置Tomcat等服务器,提供自动化配置和生产就绪功能。文章介绍了Spring Boot的简介、优点,并通过案例展示了如何创建Controller,讲解了核心配置文件如Application.yaml的使用,以及配置文件属性值的注入方法。此外,还探讨了多环境配置的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Springboot概述

简介

Spring Boot是基于Spring框架开发的全新框架,其设计目的是简化新Spring应用的初始化搭建和开发过程。
Spring Boot整合了许多框架和第三方库配置,几乎可以达到开箱即用

优点

  1. 可快速构建独立的Spring应用
  2. 直接嵌入Tomcat、Jetty和Undertow服务器(无需部署WAR文件)
  3. 提供依赖启动器简化构建配置
  4. 极大程度的自动化配置Spring和第三方库
  5. 提供生产就绪功能
  6. 极少的代码生成和XML配置

Springboot案例

  1. 选择版本
    以2.4.5为例子
  2. 添加一个web场景启动器
		<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
  1. 创建Controller

@Controller
public class UserController {
    @RequestMapping("test")
    public String test(){
        System.out.println("UserController.test");
        return  "";
    }
}

启动类要在根目录,扫描启动类所在包以及子包
`
@SpringBootApplication
@SpringBootConfiguration
当前启动类为放到Spring容器
@EnableAutoConfiguration
@AutoConfigurationPackage
扫描当前包,完成自己编写的类交给Spring管理
@Import({AutoConfigurationImportSelector.class})
完成Spring和SrpingMVC配置的内容,自动配置

Spring Boot核心配置和注解

全局配置文件

常用有Application.yaml 配置文件和Application.properties文件,常用前者,后者等级比前者高

##key:(空格)value

server:
    port: 8081
    path: /hello
spring:
  datasource:
    driver-class-name:
    url:
    data-username:
    data-password:
  mvc:
    view:
      prefix:
      suffix:

配置文件属性值注入

  1. 使用 @Component和@ConfigurationProperties(prefix = “xxx”)

例子

@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private int id;      
    public void setId(int id) {
        this.id = id;}}

注意:使用@ConfigurationProperties注解批量注入属性值时,要保证配置文件中的属性与对应实体类的属性一致,否则无法正确获取并注入属性值。

  1. 使用@Value注入属性
@Component
public class Person {
@Value("${person.id}")//使用@Value注解对每一个属性注入设置,免去了属性setXX()方法
    private int id;      
}

  1. 使用@PropertySource加载配置文件
    创建test.yml
@Configuration   
@PropertySource("classpath:test.properties
@EnableConfigurationProperties(MyProperties.class) 
@ConfigurationProperties(prefix = "test}
public class MyProperties {
}

多环境配置

在实际开发中,应用程序通常需要部署到不同的运行环境中,例如开发环境、测试环境、生产环境等。不同的环境可能需要不同的环境配置,针对这种情况,不可能手动变更配置文件来适应不同的开发环境,此时就需要对项目进行多环境配置。

  1. 多环境配置文件
文件名作用
application_dev.yaml配置开发环境
application_prod.yaml配置生产环境
application_test.yaml配置测试环境

在application.yaml中配置

# 开发环境
spring:
  profiles:
    active: dec
# 生产环境
spring:
  profiles:
    active: prod
# 测试环境
spring:
  profiles:
    active: test
  1. 在主配置配置中分别配置
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值