文章目录
SpringBoot框架详解(二)springboot入门
日日精进,虔诚专注
第二章
1.介绍
springboot 是spring中的一个成员,可以简化spring,springmvc的使用。它的核心还是ioc容器。
特点:
-
创建spring应用
-
内嵌tomcat,jetty或者udertow服务器,默认是tomcat服务器。
-
提供了starter起步依赖,简化应用的配置。
比如使用mybatis框架,需要在spring项目中,配置mybatis的对象SqlSessionFactory,dao的代理对象,在springboot项目中,在pom.xml里面,加入mybatis-spring-boot-starter依赖。
-
尽可能去配置spring和第三方库。叫做自动配置(就是spring中的,第三方库中的对象都创建好,放到容器中,开发人员可以直接使用)
-
提供了健康检查,统计,外部化配置。
-
不用生成代码,不适用xml,自动配置。
2. 创建springboot项目
2.1 第一种方式,使用spring提供的初始化器,就是向导创建springboot应用。
idea中spring initializr 中勾选default
使用的地址:https://start.spring.io
目录
-
resources
- static文件夹 放静态资源(js,css,图片)
- templates 放置模板文件
- application.properties 是springboot重要的配置文件。
-
pom.xml文件
<?xml version="1.0" encoding="UTF-8"?> <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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <!-- springboot的父项目--> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.3</version> <relativePath/> <!-- lookup parent from repository --> </parent> <!-- 当前项目的坐标gav--> <groupId>com.firewolf</groupId> <artifactId>002-springboot-first</artifactId> <version>1.0.0</version> <name>002-springboot-first</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <!-- 没有版本号是因为用的父版本的版本号--> <!-- web起步依赖(springmvc功能)--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <!-- 插件--> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
2.2 第二种方式,使用springboot提供的初始化器,使用的国内的地址。
idea中spring initializr 中勾选custom 填写
国内地址:https://start.springboot.io
@Controller
public class HelloSpringBoot {
@RequestMapping("/hello")
@ResponseBody
public String helloSpringBoot(){
return "欢迎使用SpringBoot框架";
}
}
3.注解的使用
@SpringBootApplication
符合注解:由;
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan 组成
-
@SpringBootConfiguration
由下面的注解组成
@Configuration @Indexed public @interface SpringBootConfiguration { @AliasFor( annotation = Configuration.class ) boolean proxyBeanMethods() default true; }
说明:使用了@SpringBootConfiguration注解标注的类,可以作为配置文件使用的,可以使用Bean生命对象,注入到容器。
-
@EnableAutoConfiguration
启用自动配置,把java对象配置好,注入到spring容器中。例如可以把mybatis的对象创建好,放入到容器中。
-
@ComponentScan
@ComponentScan 扫描器,找到注解,根据注解的功能创建对象,给对象赋值。 默认扫描的包:@ComponentScan所在的类所在的包和子包。
4. SpringBoot 的配置文件
配置文件名称:application
拓展名:
- properties(k=v);
- yml(k:v)
使用application.properties或者使用application.yml
4.1. application.properties设置端口和上下文
# 设置端口号
server.port=8082
# 设置访问应用上下文路径。contextpath
server.servlet.context-path=/myboot
http://localhost:8082/myboot/hello
4.2. application.yml(推荐)
server:
port: 8083
servlet:
context-path: /myboot2
PS:不要两个一起用
4.3.多环境配置
有开发环境,测试环境,上线环境。
每个环境都有不同的配置信息,例如端口,上下文件,数据库url,用户名,密码等等。
使用多环境配置文件,可以方便的切换不同的配置。
使用方式:创建多个配置文件,名称规则:application-环境名称.properties(yml)
创建开发环境的配置文件:application-dev.properties(application-dev.yml)
创建测试使用的配置:application-test.properties(yml)
创建上线使用的配置:application-online.yml
在application.properties(yml)
# 激活使用哪个配置文件
# 使用dev
# spring.profiles.active=dev
# 使用test的环境
spring.profiles.active=test
4.5. SpringBoot自定义配置
1. @Value注解
-
Application.properties
# 配置端口号 server.port=8082 #context-path 上下文路径 server.servlet.context-path=/myboot #自定义key-value school.name=喝水吃饭大学 school.website=www.bytedance.com school.address=北京的大兴区 site=www.baidu.com
-
HelloController.class
@Controller public class HelloController { @Value("${server.port}") private Integer port; @Value("${server.servlet.context-path}") private String contextPath; @Value("${school.name}") private String name; @Value("${school.website}") private String site; @RequestMapping("/data") @ResponseBody public String queryDate(){ return name+","+"site"+site+",项目的访问地址"+contextPath+",使用的端口="+port; } }
2. @ConfigurationProperties
将整个文件映射成一个对象,用于自定义配置项比较多的情况。
@Component
// school 是配置文件属性的前缀
@ConfigurationProperties(prefix = "school")
public class SchoolInfo {
private String name;
private String website;
private String address;
// 要有get和set
@Override
public String toString() {
return "SchoolInfo{" +
"name='" + name + '\'' +
", website='" + website + '\'' +
", address='" + address + '\'' +
'}';
}
}
@Controller
public class HelloController {
@Resource
private SchoolInfo info;
@RequestMapping("/info")
@ResponseBody
public String queryInfo(){
return "SchoolInfo对象=="+info.toString();
}
}
<!-- 处理ConfigurationProperties有关的元数据-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
5.使用jsp
Springboot不推荐使用jsp,而是使用模板技术代替jsp。
使用jsp需要配置:
-
加入处理jsp的依赖。负责编译jsp文件
<dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency
-
如果需要使用servlet,jsp的功能。
<!-- servlet 依赖的 jar 包--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> </dependency> <!-- jsp 依赖 jar 包--> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version> </dependency> <!--如果使用 JSTL 必须添加该依赖--> <!--jstl 标签依赖的 jar 包 start--> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency>
-
创建一个存放jsp的目录,一般叫做webapp
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>jsp文件</title> </head> <body> <h3>使用jsp,显示Controller中的数据${data}</h3> </body> </html>
-
需要在pom.xml指定jsp文件编译后的存放目录。
META-INF/resources
<build> <!-- 指定jsp编译后的存放目录--> <resources> <resource> <!-- jsp原来的目录--> <directory>src/main/webapp</directory> <!-- 指定编译后的存放目录--> <targetPath>META-INF/resources</targetPath> <!-- 指定处理的目录和文件--> <includes> <!-- 任意目录下的任意文件--> <include>**/*.*</include> </includes> </resource> </resources>
-
创建Controller,访问jsp
package com.firewolf.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; @Controller public class JspController { // public String doJsp(HttpServletRequest request){ // // request.setAttribute("data","Springboot使用jsp"); 视图的逻辑名称 // return "index"; // // } /** * * */ @RequestMapping("myjsp") public String doJsp(Model model){ // 把数据放到request作用域 model.addAttribute("data","SpringBoot使用jsp"); // 视图的逻辑名称 return "index"; } }
-
在application.propertis文件配置视图解析器。
#配置端口号 server.port=9090 server.servlet.context-path=/myboot # 配置视图解析器 # / = src/main/webapp spring.mvc.view.prefix=/ spring.mvc.view.suffix=.jsp
6.使用容器,springboot中使用ApplicationContext
通过代码,从容器中获取对象。
通过SpringApplication.run(Application.class, args);返回值获取容器。
public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
return run(new Class[]{primarySource}, args);
}
public interface ConfigurableApplicationContext extends ApplicationContext, Lifecycle, Closeable {}
ConfigurableApplicationContext :接口,是ApplicationContext的子接口。
-
创建一个接口
package com.firewolf.service; public interface UserService { void sayHello(String name); }
-
创建接口的实现类
package com.firewolf.service.impl; import com.firewolf.service.UserService; import org.springframework.stereotype.Service; @Service("userService") public class UserServiceImpl implements UserService { @Override public void sayHello(String name) { System.out.println("执行了业务方法的sayHello:"+name); } }
-
获取容器对象。
package com.firewolf; import com.firewolf.service.UserService; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; @SpringBootApplication public class Application { public static void main(String[] args) { // 获取容器对象 ConfigurableApplicationContext ctx=SpringApplication.run(Application.class, args); // 从容器中获取对象 UserService userService=(UserService) ctx.getBean("userService"); userService.sayHello("李四"); } }
这个操作可以用于测试项目的部分功能,比如不想启动全部项目。
7.CommandLineRunner ,ApplicationRunner接口
有时候需要在容器启动后执行一些内容。比如读取配置文件,数据库连接之类的。SpringBoot给我们提供了两个接口实现这种需求。
-
CommandLineRunner
run方法为ApplicationArguments
-
ApplicationRunner
run方法为CommandLineRunner接口中的run方法为String数组。
-
两个接口效果一样。
package com.firewolf;
import com.firewolf.service.HelloService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import javax.annotation.Resource;
@SpringBootApplication
public class Application implements CommandLineRunner {
@Resource
private HelloService helloService;
public static void main(String[] args) {
System.out.println("准备创建容器对象");
// 创建容器对象
SpringApplication.run(Application.class, args);
System.out.println("容器对象创建之前");
}
@Override
public void run(String... args) throws Exception {
String str = helloService.sayHello("lisi");
System.out.println("调用容器的对象"+str);
// 可做自定义的操作,比如读取文件,数据库的等等
System.out.println("在容器对象创建好,执行的方法");
}
}