SpringBoot第一部分

Spring Boot 是一个基于 Spring 框架的开箱即用项目,通过自动配置和约定优于配置的原则极大简化了项目的初始搭建与开发部署流程。它内置了 Tomcat、Jetty 等 Web 服务器,可直接打包为可独立运行的 JAR 文件,无需依赖外部容器


注解配置

以下注解可用于配置和获取bean,用以取代XML配置文件

注解 作用位置 功能描述
@Configuration 声明当前类为配置类,相当于 XML 配置文件
@ComponentScan 自动扫描指定包下带有 @Repository@Service@Controller@Component 的类,并由 IoC 容器进行实例化和维护
@Component 通用注解,声明该类为 Spring 组件,由 IoC 容器管理
@Bean 方法 声明当前方法的返回值为一个 Bean,相当于 XML 中的 <bean> 标签
@Value 字段、方法参数 用于从 properties 文件中获取指定 key 对应的 value 值

@Bean注解使用

在配置类中实例化

@Configuration
@ComponentScan("com.example.springboot")
public class IocConfig {
@Bean
public AccountDao accountDao(){
return new AccountDao();
}
}

获取实例

public class Starter02 {
public static void main(String[] args) {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(IocConfig.class);
IocConfig iocConfig = ac.getBean(IocConfig.class);
AccountDao accountDao = iocConfig.accountDao();
}
}

@Value注解使用

准备配置文件,如user.properties

user.userName = admin
user. userPasswd = admin

配置类通过@PropertySource注解加载配置文件,@Value用于获取值

@Configuration
@ComponentScan("com.example.springboot")
@PropertySource(value = "classpath:user.properties")
public class IocConfig {

@Value("${user.userPasswd}")
private String adminPasswd;

}

在配置类中加载后,其他bean对象都可以获得载入的配置文件属性

元注解与组合注解

元注解可以标记在注解上组成组合注解,组合注解具有元注解的原始功能,我们也可以自定义组合注解。自定义的组合注解一般具有@Target@Retention@Documented三个元注解,分别表示该注解作用的对象、保留时机和注解信息是否存在于JavaDoc中

自定义组合注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Configuration
@ComponentScan
public @interface NewCompScan {
String[] value() default {};
}

SpringMVC的注解配置

编写配置类取代XML配置文件

@Configuration
// 在@Configuration注解的配置类中添加,用于为该应用添加SpringMVC的功能
@EnableWebMvc
@ComponentScan("com.xxxx.springboot")
public class MVCConfig {

@Bean
public InternalResourceViewResolver viewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}

使用WebApplicationInitializer接口的实现类实现配置类的功能,实现该接口的类都能在web应用启动时被加载

public class WebInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(MVCConfig.class);
ctx.setServletContext(servletContext);
ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
}

关于配置拦截器,需要MVCConfig配置类实现 WebMvcConfigurer接口,loginInterceptor为我们定义的拦截器类

@Configuration
public class MVCConfig implements WebMvcConfigurer {

@Bean
public LoginInterceptor loginInterceptor() {
return new LoginInterceptor();
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/login", "/css/**", "/js/**", "/images/**");
}
}

SpringBoot程序编写

环境配置

配置依赖项,SpringBoot项目必须要将<parent>标签设置为SpringBoot的parent,该parent包含了大量默认配置,帮助开发者自动选择依赖版本,简化了开发程序

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>

配置插件,用于方便打包环节

<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>

编写源码

编写Controller类

@Controller
public class HelloController {

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

创建启动程序

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

启动main方法,就可以默认运行在8080端口下


SpringBoot自定义配置

Banner图标

SpringBoot启动的默认Banner图标

  .   ____          _            __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.7.18)

我们可以在src/main/resources目录下新建banner.txt文件,这样程序启动时会加载我们自定义的图标文件

SpringBoot配置文件

Spring Boot 默认会读取全局配置文件,配置文件名固定为:application.propertiesapplication.yml,放置在 src/main/resources 资源目录下,使用配置文件来修改 SpringBoot 自动配置的默认值

在 resources 资源目录下添加 application.properties 文件,配置信息如下:

### 项目启动端口号配置
server.port=8080
### 项目访问上下文路径
server.servlet.context-path=/mvc

### 数据源配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/DBName?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root

Peofile配置

Profile 是 Spring 用来针对不同环境对不同配置提供支持的全局 Profile 配置使用 application-{profile}.yml,比如 application-dev.ymlapplication-test.yml

通过在 application.yml 中设置 spring.profiles.active=test|dev|prod 来动态切换不同环境,具体配置如下:

application-dev.yml 开发环境配置文件

server:
port: 8989

application-test.yml 测试环境配置文件

server:
port: 9999

application.yml 主配置文件,使用active属性切换环境

spring:
profiles:
active: dev

日志配置

Spring Boot 默认使用 LogBack 日志系统,如果不需要更改为其他日志系统如 Log4j2 等,则无需多余的配置,LogBack 默认将日志打印到控制台上。如果要使用 Log4j2,原则上是需要添加 dependency 依赖的

<!-- Spring Boot Web Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<!-- 排除默认的 Logback -->
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>

<!-- 添加 Log4j2 Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

启动类演示使用日志

@SpringBootApplication
public class Starter {
private static Logger logger = LoggerFactory.getLogger(Starter.class);

public static void main(String[] args) {
logger.info("SpringBoot LogInfoTest");
SpringApplication.run(Starter.class, args);
}
}

修改日志输出格式,将其添加进application.yml

logging:
pattern:
console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger - %msg%n"
level: debug
file:
path: "."
name: "springboot.log"

视图集成

FreeMark模板引擎

引入依赖项

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

Freemarker 默认视图路径为 resources/templates 目录(由自动化配置类 FreemarkerProperties 决定),该目录可以在application.yml中进行修改

spring:
freemarker:
suffix: .ftl
content-type: text/html
charset: UTF-8
template-loader-path: classpath:/views/

FreeMark的的模板文件后缀是.ftl

Thymeleaf渲染引擎

SpringBoot 支持多种视图技术集成,并且 SpringBoot 官网推荐使用 Thymeleaf 作为前端视图页面,这里实现 Thymeleaf 视图集成,借助入门项目引入 Thymeleaf 环境配置

引入依赖项

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

Thymeleaf 默认视图路径为 resources/templates 目录(由自动化配置类 ThymeleafProperties 决定),该目录可以在application.yml中进行修改

spring:
thymeleaf:
prefix: classpath:/html/
# 关闭 thymeleaf 页面缓存
cache: false

Thymeleaf可以直接对html进行渲染,使用其特定的语法即可识别进行渲染

<h2 th:text="${msg}"></h2>

静态资源访问

resources 目录下创建 static 或者 public 目录,存放imagesjscss 等静态资源文件,默认的路径有resources/publicresources/staticresources/

若要自定义静态资源路径,可以在application.yml中添加

spring:
resources:
static-locations: classpath:/public/,classpath:/static/,classpath:/path/to/your/static

应用打包

Jar包部署

在 IDEA 下配置 clean compile package -Dmaven.test.skip=true 执行打包命令,target 目录得到待部署的项目文件

打包完成后,使用命令行即可编译jar包运行web程序

War包部署

修改pom.xml<packaging>标签改为war,默认为jar

忽略内嵌Tomcat,使用provided属性忽略

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>

配置生成的war包属性

<build>
<!-- 配置生成的 war 文件名 -->
<finalName>springboot</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

启动类继承SpringBootServletInitializer并重写configure()方法,指定外部tomcat读取项目入口方法

@SpringBootApplication
public class Starter extends SpringBootServletInitializer {
private static Logger logger = LoggerFactory.getLogger(Starter.class);

public static void main(String[] args) {
logger.info("SpringBoot LogInfoTest");
SpringApplication.run(Starter.class, args);
}

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(Starter.class);
}
}

执行maven打包命令,生成war包