hello world项目
看课的一些笔记。
- 指定设置
- 父工程
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.2</version>
</parent>
- 导入spring场景包
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
- 写代码
4.1.主程序
/**
* 主程序类:
* @SpringBootApplication是一个SpringBoot应用
* */
@SpringBootApplication
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class,args);
}
}
4.2.业务
@ResponseBody
@Controller
public class HelloController {
@RequestMapping("/hello")
public String handle01(){
return "hello,SpringBoot2!";
}
}
/**@ResponseBody: 返回的内容直接写在浏览器上而不是跳转到哪个页面
*@ResponseBody + @Controller = @RestController
*@RestController:该Controller 返回的内容都是写在浏览器上的
**/
4.3.访问即可
简化配置
所有配置都抽取在一个文件:application.properties
详细情况见官网:SpringBoot2-2.7.2的详细配置
简单部署
1.pom.xml写能打成jar包的插件
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
2.打成jar包
3.部署
找到target文件夹,文件夹直接cmd运行jar
依赖管理
父工程
导入父工程——实现SpringBoot特点:依赖管理
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.2</version>
</parent>
spring-boot-starter-parent还有一个父项目
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.7.2</version>
</parent>
<!--<description>Parent pom providing dependency and plugin management for applications built with Maven</description>-->
dependencies中的properties中声明了大部分jar包的依赖及其版本,
默认值就是当前使用版本SpringBoot支持的版本(自动版本仲裁机制)。
修改版本
1.找要用的版本:
仓库找版本:MVN-Repository
2.在项目pom.xml文件中写properties进行声明(感觉有点像子类的重写哦)
<properties>
<mysql.version>5.1.43</mysql.version>
</properties>
场景开发包starter
spring-boot-starter-* 引入一个starter,相关的所有常规依赖都自动引入
所有依赖的底层依赖:也是SpringBoot的核心依赖:spring-boot-starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.7.2</version>
<scope>compile</scope>
</dependency>
starter相关:官方starter和第三方starter
自动配置
自动配置的autoconfigure包中有很多场景,自己的pom写了什么starter就会开启什么场景
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.7.2</version>
<scope>compile</scope>
</dependency>
Tomcat,springMVC等自动配置
1.引入依赖(一般场景包或者父工程都引入了)
2.自动配好
自动配好常见的web功能
在主程序中拿到IOC容器后getBean()打印会发现已经写好了很多bean,
比如dispachServlet,文件上传的multipartResolver;视图解析器viewResolver;字符编码器characterEncodingFilter;
默认包扫描
以前要在配置里写controller在哪个包里,去哪个包扫描
springboot有默认的default包,只要是MainApplication的同级包或子包都默认扫描到
如果在MainApplicatoion外面的包里:
1.@ComponentScan():包扫描
//删除@SpringBootApplication注解-二者等价
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("包的名字")
2.或者主程序中写明scanBasePackages
@SpringBootApplication(scanBasePackages = "包的名字")
配置有默认值
某个类声明了这些配置文件的属性,这个类会在容器中创建对象