Sring Boot部分详解

Spring_Boot

1.Spring框架发展史

在Spring1.x时代,都是通过xml文件配置bean,随着项目的不断扩大,需要将xml配置分放到不同
的配置文件中,需要频繁的在java类和xml配置文件中切换。

随着JDK 1.5带来的注解支持,Spring2.x可以使用注解对Bean进行申明和注入,大大的减少了xml
配置文件,同时也大大简化了项目的开发。
那么,问题来了,究竟是应该使用xml还是注解呢?
最佳实践:

  1. 应用的基本配置用xml,比如:数据源、资源文件等;
  2. 业务开发用注解,比如:Service中注入bean等;

从Spring3.x开始提供了Java配置方式,使用Java配置方式可以更好的理解你配置的Bean,现在我
们就处于这个时代,并且Spring4.x、Spring5.x和Spring Boot都推荐使用java配置的方式。

2.Spring5.X应用零配置开发

Spring 框架从5.x版本推荐使用注解形式来对java应用程序进行开发与配置,并且可以完全替代原始
的XML+注解形式的开发,在使用注解形式进行项目开发与环境配置时,Spring 框架提供了针对环境配置
与业务bean开发相关注解。

2.1. 注解

2.1.1. 声明Bean注解
@Component:组件 没有明确规定其角色,作用在类级别上声明当前类为一个业务组件,被Spring Ioc 容
器维护;
@Service:在业务逻辑层(Service 层)类级别进行声明;
@Repository:在数据访问层(dao 层) 类级别声明;
@Controller:在展现层(MVC) 使用 标注当前类为一个控制器
2.1.2. 注入Bean注解
@AutoWired:Spring 官方提供注解
@Inject:JSR-330 提供注解(标准制定方)
@Resource:JSR-250 提供注解

以上三种注解在Set 方法或属性上声明,一般情况下通用一般开发中更习惯声明在属性上,代码简
洁清晰。基于5.x 注解配置方式简化了xml 配置,应用程序开发与xml 环境配置均通过相应注解来实

2.1.3. Spring5.x 中配置与获取Bean注解
@Configuration:作用与类上,将当前类声明为一个配置类,相当于一个xml 配置文件
@ComponentScan:自动扫描指定包下标注有@Repository,@Service,@Controller
@Component:注解的类并由Ioc 容器进行实例化和维护
@Bean::作用于方法上,相当于xml 文件中<bean> 声明当前方法返回值为一个bean
@Value:获取properties 文件指定key value值

2.2. 实例1-Ioc中Bean的实例化与获取

2.2.1. 创建Spring 普通工程并添加坐标相关配置

<dependencies>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-context</artifactId>
		<version>5.2.3.RELEASE</version>
	</dependency>
</dependencies>
<build>
	<plugins>
		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-compiler-plugin</artifactId>
			<version>2.3.2</version>
<configuration>
		<source>1.8</source>
		<target>1.8</target>
		<encoding>utf-8</encoding>
</configuration>
		</plugin>
	</plugins>
</build>
2.2.2. 添加源代码

创建UserDao ,UserService Bean 对象

// UserDao.java
@Repository
public class UserDao {
public void test(){
	System.out.println("UserDao.test...");
	}
}
// UserService.java
@Service
public class UserService {
	@Resource
	private UserDao userDao;
public void test(){
	System.out.println("UserService.test...");
		userDao.test();
}
}
2.2.3. 创建IocConfig配置类
// Ioc 容器配置 Java 代码实现
@Configuration
@ComponentScan("com.liuxidong.springboot")
public class IocConfig {
}
2.2.4. 创建启动类执行测试
public class Starter {
public static void main(String[] args) {
AnnotationConfigApplicationContext ac=new
			AnnotationConfigApplicationContext(IocConfig.class);
				UserService userService= ac.getBean(UserService.class);
					userService.test();
	}
}

2.3. 实例2-读取外部配置文件

2.3.1. 准备properties 配置文件

src/main/resources 目录下添加user.properties jdbc.roperties 文件

# user.properties
user.userName=admin
user.password=admin
# jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/hr?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root
2.3.2. @PropertySource加载properties配置文件
@Configuration
@ComponentScan("com.shsxt")
@PropertySource(value =
{"classpath:jdbc.properties","classpath:user.properties"})
		public class IocConfig {
				@Value("${jdbc.driver}")
				private String url;
				@Value("${jdbc.url}")
				private String driver;
				@Value("${jdbc.username}")
				private String userName;
				@Value("${jdbc.password}")
				private String password;
@Bean
public AccountDao accountDao(){
	return new AccountDao();
}
// 控制台打印属性值信息
public void showConfigInfo(){
	System.out.println("driver:"+driver+":url:"+url);
	System.out.println(":userName:"+userName+":password:"+password);
	}
}
2.3.3. 其他Bean对象获取properties文件内容
@Service
public class UserService {
@Resource
private UserDao userDao;
@Resource
	private AccountDao accountDao;
	@Value("${user.userName}")
	private String userName;
	@Value("${user.password}")
	private String password;
public void test(){
		System.out.println("UserService.test...");
			userDao.test();
			accountDao.test();
		System.out.println("userName:"+userName+":password:"+password);
		}
}

启动Starter 查看控制台输出内容效果

3.Spring mvc应用零配置开发

3.1. 创建Spring Mvc Web工程

pom.xml添加坐标相关配置

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.liuxidong</groupId>
  <artifactId>spring_boot_02</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>spring_boot_02 Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>5.2.3.RELEASE</version>
  </dependency>
  <!-- spring mvc -->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.3.RELEASE</version>
  </dependency>
  <!-- web servlet -->
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
  </dependency>

  </dependencies>
  <build>
    <finalName>spring_boot_02</finalName>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>2.3.2</version>
          <configuration>
            <source>1.8</source>
            <target>1.8</target>
            <encoding>utf-8</encoding>
          </configuration>
        </plugin>
        <plugin>
          <groupId>org.eclipse.jetty</groupId>
          <artifactId>jetty-maven-plugin</artifactId>
          <version>9.4.27.v20200227</version>
        </plugin>
      </plugins>
  </build>
</project>

3.2. 添加源代码

package com.liuxidong.springboot.controller;

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

/**
 * @author lxd
 * #Description UserController
 * #Date: 2023/4/17 13:26
 */
@Controller
public class UserController {
    @RequestMapping("/index")
    public String index(){

        return "index";
    }
}

3.3. 添加视图

<%--
  Created by IntelliJ IDEA.
  User: 86131
  Date: 2023/4/17
  Time: 13:28
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>赵丽颖</h1>
</body>
</html>

3.4. SpringMvc配置类添加

package com.liuxidong.springboot.config;

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;


/**
 * @author lxd
 * #Description MvcConfig
 * #Date: 2023/4/17 13:29
 */
@Configurable
@EnableWebMvc
@ComponentScan("com.liuxidong.springboot")
public class MvcConfig {
    @Bean
    public InternalResourceViewResolver viewResolver(){
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }
}

3.5. 入口文件代码添加

package com.liuxidong.springboot;

import com.liuxidong.springboot.config.MvcConfig;
import org.springframework.stereotype.Controller;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.Registration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;


/**
 * @author lxd
 * #Description WebInitializer
 * #Date: 2023/4/17 13:33
 */

public class WebInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext c = new AnnotationConfigWebApplicationContext();
        // 注册Mvc 配置信息
        c.register(MvcConfig.class);
        // 设置ServletContext 上下文信息
        c.setServletContext(servletContext);
        // 配置转发器Dispatcher
        ServletRegistration.Dynamic
                servlet=servletContext.addServlet("dispatcher",new DispatcherServlet(c));
        servlet.addMapping("/");
// 启动时即实例化Bean
        servlet.setLoadOnStartup(1);
    }

}

3.6. 部署与测试

在这里插入图片描述

4.Spring boot框架概念、优势与快速入门

4.1. 概念

spring boot的设计就是为了尽可能快的跑起来spring应用程序,并且尽可能减少配置文件;它默认了很多框架的使用方式,就好比maven整合了所有jar包,spring即整合了所有的框架

4.2. 优势

spring boot实在spring的基础上面搭建的框架,目的就是为了简化Spring项目的搭设和开发过程。不存在冲突的问题
**1. 自动配置Sring-boot-starter开箱即用依赖模块
2. 简化统一配置文件
3. 监控管理actuator
4. 内嵌了如Tomcat,Jetty,所有的依赖都打到一个jar包里,可直接java -jar运行 **

4.3. spring boot 快速入门

4.3.1. 环境

Idea Maven Jdb1.8+ Spring Boot

4.3.2. 创建Maven普通项目

在这里插入图片描述

4.3.3. 添加坐标依赖
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.liuxidong</groupId>
  <artifactId>spring_boot_03</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>spring_boot_03</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

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

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

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

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

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


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

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>

4.3.4. 添加源代码
package com.liuxidong.springboot.controller;

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

/**
 * @author lxd
 * #Description UserController
 * #Date: 2023/4/17 14:47
 */
@Controller
public class UserController {
    @RequestMapping("hello")
    @ResponseBody
    public String hello(){
        return "赵丽颖";
    }
}

4.3.5. 创建启动程序
package com.liuxidong.springboot;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;



/**
 * @author lxd
 * #Description StraterApplication
 * #Date: 2023/4/17 14:51
 */
@SpringBootApplication
public class StarterApplication {
    private static Logger logger = LoggerFactory.getLogger(StarterApplication.class);
    public static void main(String[] args) {
        logger.info("SpringBoot 应用开始启动...");
        SpringApplication.run(StarterApplication.class);
    }
}

4.3.6. 启动Spring boot应用并测试

这里运行main方法即可 通过浏览器访问http://localhost:8080/index 效果如下:
在这里插入图片描述

5.Spring boot核心配置

5.1. 自定义Banner与Banner关闭

在这里插入图片描述在搭建Spring Boot项目环境时,程序启动后会在控制台打印醒目的SpringBoot图标,图标描述了
Spring Boot 版本信息,这是Spring Boot项目与Spring项目启动区别较大的地方,Spring Boot通过默认Banner在程序启动时显示应用启动图标,当然图标我们也可以进行自定义。

5.1.1. Banner图标自定义

Spring Boot项目启动时默认加载src/main/resources 目录下的banner.txt 图标文件,如果该目录文件未提供,则使用Spring Boot 默认图标打印在main 目录下新建resources 资源目录,并在该目录下新建banner.txt 文本文件。
打开网址: http://patorjk.com/software/taag/#p=display&f=Graffiti&t=Type%20Something%20
在线生成图标对应文本并将文本内容copy 到banner.txt 中
在这里插入图片描述
启动Spring Boot应用打印如下:
在这里插入图片描述

5.1.2.Banner关闭

如果启动时不想要看到启动图标,这里也可以通过代码进行关闭操作,修改StarterApplication 设置BannerMode值为Banner.Mode.OFF,启动Spring Boot 应用关闭图标输出功能即可

@SpringBootApplication
public class StarterApplication {
public static void main(String[] args) {
SpringApplication springApplication=new
SpringApplication(StarterApplication .class);
// 设置banner 图标关闭
springApplication.setBannerMode(Banner.Mode.OFF);
springApplication.run();
}
}

5.2. Spring Boot配置文件

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

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

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

或者application.yml 文件

## 端口号 上下文路径
server:
port: 8989
servlet:
context-path: /mvc
## 数据源配置
spring:
datasource:
type: com.mchange.v2.c3p0.ComboPooledDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/hr
username: root
password: root

5.3. Profile配置

Profile 是Spring 用来针对不同环境对不同配置提供支持的全局Profile配置使用application-
{profile}.yml,比如application-dev.yml ,application-test.yml。
通过在application.yml中设置spring.profiles.active=test|dev|prod 来动态切换不同环境。

5.4. 日志配置

在开发企业项目时,日志的输出对于系统bug 定位无疑是一种比较有效的方式,也是项目后续进入
生产环境后快速发现错误解决错误的一种有效手段,所以日志的使用对于项目也是比较重要的一块功
能。
Spring Boot默认使用LogBack日志系统,如果不需要更改为其他日志系统如Log4j2等,则无需多
余的配置,LogBack默认将日志打印到控制台上。如果要使用LogBack,原则上是需要添加
dependency依赖的

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

因为新建的Spring Boot项目一般都会引用 spring-boot-starter 或者 spring-boot-starterweb ,而这两个起步依赖中都已经包含了对于 spring-boot-starter-logging 的依赖,所以,无需额外
添加依赖。

5.4.1. 项目中日志信息输出

Starter 启动类中添加Log 日志类,控制台打印日志信息。

package com.xxxx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Starter {
private static Logger logger = LoggerFactory.getLogger(Starter.class);
public static void main(String[] args) {
logger.info("SpringBoot 应用开始启动...");
SpringApplication.run(Starter.class);
}
}
5.4.2. 日志输出格式配置
logging:
pattern:
console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger- %msg%n"
level: debug
file:
path: "."
name: "springboot.log"

更多日志输出,参考

6.Freemarker&Thymeleaf模板集成

6.1.Freemarker视图集成

SpringBoot内部支持Freemarker 视图技术的集成,并提供了自动化配置类
FreeMarkerAutoConfiguration,借助自动化配置可以很方便的集成Freemarker基础到SpringBoot环
境中。这里借助入门项目引入Freemarker环境配置。

6.1.1. starter坐标引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
6.1.2.添加Freemarker 配置信息

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

spring:
freemarker:
suffix: .ftl
content-type: text/html
charset: UTF-8
template-loader-path: classpath:/views/
6.1.3. 编写IndexController 控制器转发视图
package com.liuxidong.springboot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author lxd
 * #Description IndexController
 * #Date: 2023/4/17 16:20
 */
@Controller
public class IndexController {
   /* @RequestMapping("index")
    public String index(){
        return "index";
    }*/

    @RequestMapping("index")
    public String index(Model model){
        model.addAttribute("msg","赵丽颖");
        return "index";
    }
}

6.1.4. views目录下添加index.ftl视图

在这里插入图片描述

6.1.5. 启动Starter访问

在这里插入图片描述

6.2.Thymeleaf视图集成

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

6.2.1. starter坐标引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
6.2.2. 添加Thymeleaf 配置信息

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


server:
  port: 5555

spring:
  thymeleaf:
    prefix: classpath:/html/
    cache: false
6.2.3. 编写IndexController 控制器转发视图
package com.liuxidong.springboot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author lxd
 * #Description IndexController
 * #Date: 2023/4/17 16:20
 */
@Controller
public class IndexController {
    @RequestMapping("index")
    public String index(Model model){
        model.addAttribute("msg","赵丽颖");
        return "index";
    }
}

6.2.4. html目录下添加index.html视图
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1 th:text="${msg}"></h1>
</body>
</html>
6.2.5.启动Starter访问

在这里插入图片描述

7.静态资源文件添加与访问

从入门项目中可以看到:对于Spring Mvc 请求拦截规则为‘/’,Spring Boot 默认静态资源路径如下:

public class ResourceProperties {
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]
{"classpath:/META-INF/resources/", "classpath:/resources/",
"classpath:/static/", "classpath:/public/"};
private String[] staticLocations;
private boolean addMappings;
private final ResourceProperties.Chain chain;
private final ResourceProperties.Cache cache;

即:我们可以在resources 资源目录下存放web 应用静态资源文件。
在resources 目录下创建static 或者public 存放images、js、css等静态资源文件
浏览器访问
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值