基础入门-SpringBoot2
基础入门-SpringBoot-HelloWorld
系统要求
- Java 8
- Maven 3.3+
- IntelliJ IDEA 2019.1.2
Maven配置文件
新添内容:
<mirrors>
<mirror>
<id>nexus-aliyun</id>
<mirrorOf>central</mirrorOf>
<name>Nexus aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror>
</mirrors>
<profiles>
<profile>
<id>jdk-1.8</id>
<activation>
<activeByDefault>true</activeByDefault>
<jdk>1.8</jdk>
</activation>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
</properties>
</profile>
</profiles>
HelloWorld项目
需求:浏览发送/hello请求,响应 “Hello,Spring Boot 2”
创建maven工程
引入依赖
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.peihj</groupId>
<artifactId>springboot-03-web</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-03-web</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>jquery</artifactId>
<version>3.6.0</version>
</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>
创建主程序
package com.peihj;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
/*
主程序类
* 这个注解说明这个是一个springboot应用
* */
@SpringBootApplication
public class Springboot03WebApplication {
public static void main(String[] args) {
// 这个返回的是ioc容器
ConfigurableApplicationContext run = SpringApplication.run(Springboot03WebApplication.class, args);
String[] names = run.getBeanDefinitionNames();
for (String name : names) {
System.out.println(name);
}
}
}
编写业务
package com.peihj.Controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController // 返回字符串
//@Controller
//@ResponseBody
public class helloController {
@GetMapping("/hello")
public String hello(){
return "hello world";
}
}
运行&测试
- 运行
MainApplication
类 - 浏览器输入
http://localhost:8888/hello
,将会输出Hello, Spring Boot 2!
。
设置配置
maven工程的resource文件夹中创建application.properties文件。
# 设置端口号
server.port=8888
打包部署
在pom.xml添加
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
在IDEA的Maven插件上点击运行 clean 、package,把helloworld工程项目的打包成jar包,打包好的jar包被生成在helloworld工程项目的target文件夹内。用cmd运行java -jar boot-01-helloworld-1.0-SNAPSHOT.jar
,既可以运行helloworld工程项目。将jar包直接在目标服务器执行即可。
基础入门-SpringBoot-依赖管理特性
- 父项目做依赖管理
依赖管理
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
</parent>
上面项目的父项目如下:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.3.4.RELEASE</version>
</parent>
它几乎声明了所有开发中常用的依赖的版本号,自动版本仲裁机制
开发导入starter场景启动器
- 见到很多 spring-boot-starter-* : *就某种场景
- 只要引入starter,这个场景的所有常规需要的依赖我们都自动引入
- 更多SpringBoot所有支持的场景
- 见到的 *-spring-boot-starter: 第三方为我们提供的简化开发的场景启动器。
所有场景启动器最底层的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.3.4.RELEASE</version>
<scope>compile</scope>
</dependency>
-
无需关注版本号,自动版本仲裁
- 引入依赖默认都可以不写版本
- 引入非版本仲裁的jar,要写版本号。
-
可以修改默认版本号
- 查看spring-boot-dependencies里面规定当前依赖的版本 用的 key。
- 在当前项目里面重写配置,如下面的代码。
<properties>
<mysql.version>5.1.43</mysql.version>
</properties>
IDEA快捷键:
ctrl + shift + alt + U
:以图的方式显示项目中依赖之间的关系。alt + ins
:相当于Eclipse的 Ctrl + N,创建新类,新包等。
基础入门-SpringBoot-自动配置特性
自动配好Tomcat:
- 引入Tomcat依赖。
- 配置Tomcat。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<version>2.3.4.RELEASE</version>
<scope>compile</scope>
</dependency>
- 自动配好SpringMVC
- 引入SpringMVC全套组件
- 自动配好SpringMVC常用组件(功能)
- 自动配好Web常见功能,如:字符编码问题
- SpringBoot帮我们配置好了所有web开发的常见场景
public static void main(String[] args) {
//1、返回我们IOC容器
ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
//2、查看容器里面的组件
String[] names = run.getBeanDefinitionNames();
for (String name : names) {
System.out.println(name);
}
}
默认的包结构
- 主程序所在包及其下面的所有子包里面的组件都会被默认扫描进来
- 无需以前的包扫描配置
- 想要改变扫描路径
- @SpringBootApplication(scanBasePackages=“com.lun”)
- @ComponentScan 指定扫描路径
@SpringBootApplication
等同于
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("com.lun")
-
各种配置拥有默认值
- 默认配置最终都是映射到某个类上,如:
MultipartProperties
- 配置文件的值最终会绑定每个类上,这个类会在容器中创建对象
- 默认配置最终都是映射到某个类上,如:
-
按需加载所有自动配置项
- 非常多的starter
- 引入了哪些场景这个场景的自动配置才会开启
- SpringBoot所有的自动配置功能都在 spring-boot-autoconfigure 包里面
-
…
底层注解-@Configuration详解
基本使用
- Full模式与Lite模式
- 示例
package com.peihj.config;
import com.peihj.pojo.User;
import com.peihj.pojo.pet;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 1、配置类里面使用@Bean标注在方法上给容器注册组件,默认也是单实例的
* 2、配置类本身也是组件
* 3、proxyBeanMethods:代理bean的方法
* Full(proxyBeanMethods = true)(保证每个@Bean方法被调用多少次返回的组件都是单实例的)(默认)
* Lite(proxyBeanMethods = false)(每个@Bean方法被调用多少次返回的组件都是新创建的)
*/
@Configuration(proxyBeanMethods = true) // 告诉springboot这个是一个配置类,配置文件
public class Myconfig {
/**
* Full:外部无论对配置类中的这个组件注册方法调用多少次获取的都是之前注册容器中的单实例对象
* @return
*/
@Bean // 给容器中添加组件,以方法名作为组件的id,返回类型就是组件类型,返回的值就是组件再容器中的实例
public User user01(){
// user组件依赖了pet组件
User zhangsan = new User();
zhangsan.setName("zhangsan");
zhangsan.setAge(18);
zhangsan.setPet(tomcatpet());
return zhangsan;
}
@Bean("tom")
public pet tomcatpet(){
return new pet("tomcatpet");
}
}
@Configuration测试代码如下:
package com.peihj;
import com.peihj.config.Myconfig;
import com.peihj.pojo.User;
import com.peihj.pojo.pet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
/*
主程序类
* 这个注解说明这个是一个springboot应用
* */
/**
* 1、配置类里面使用@Bean标注再方法上给容器注册组件,默认也是单实例的。
* 2、配置类本质上也是一个组件、
* 3、proxyBeanMethods:代理bean的方法
*/
@SpringBootApplication
public class Springboot03WebApplication {
public static void main(String[] args) {
// 这个返回的是ioc容器
ConfigurableApplicationContext run = SpringApplication.run(Springboot03WebApplication.class, args);
String[] names = run.getBeanDefinitionNames();
for (String name : names) {
System.out.println(name);
}
// 从容器中获取组件,组测的组件默认产生方式是单实例的
pet tom01 = run.getBean("tom", pet.class);
pet tom02 = run.getBean("tom", pet.class);
System.out.println("组件:"+(tom01==tom02)); // 组件:true
Myconfig bean = run.getBean(Myconfig.class);
System.out.println(bean);
// @Configuration(proxyBeanMethods = true) 代理对象调用方法,springboot总是会检测这个组件是否再容器中
// 保持组件单实例
User user1 = bean.user01();
User user2 = bean.user01();
System.out.println(user1==user2); // true
/**
* @Configuration(proxyBeanMethods = true) 那么宠物是直接从容器中拿的。每次运行都会先检查容器中是否有组件,运行的快
* @Configuration(proxyBeanMethods = false) 宠物是直接new出来的,
*/
User user01 = run.getBean("user01", User.class);
pet pet= run.getBean("tom",pet.class);
System.out.println(user01.getPet() == pet); // true
}
}
最佳实战
- 配置 类组件之间无依赖关系用Lite模式加速容器启动过程,减少判断
- 配置 类组件之间有依赖关系,方法会被调用得到之前单实例组件,用Full模式(默认)
IDEA快捷键:
Alt + Ins
:生成getter,setter、构造器等代码。Ctrl + Alt + B
:查看类的具体实现代码。
底层注解-@Import导入组件
- @Bean、@Component、@Controller、@Service、@Repository,它们是Spring的基本标签,在Spring-Boot中并未改变它们原来的功能。
- @ComponentScan 在SpringBoot-自动配置特性有用例。
- @Import({User.class,DBHelper.class})给容器中自动创建出这两个类型的组件、默认组件的名字就是全类名。
@Import({User.class, DBHelper.class})
@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
public class MyConfig {
}
测试类:
//1、返回我们IOC容器
ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
//...
//5、获取组件
String[] beanNamesForType = run.getBeanNamesForType(User.class);
for (String s : beanNamesForType) {
System.out.println(s);
}
DBHelper bean1 = run.getBean(DBHelper.class);
System.out.println(bean1);
底层注解-@Conditional条件装配
条件装配:满足Conditional指定的条件,则进行组件注入
用@ConditionalOnMissingBean举例说明:
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(name = "tom")//没有tom名字的Bean时,MyConfig类的Bean才能生效。
public class MyConfig {
@Bean
public User user01(){
User zhangsan = new User("zhangsan", 18);
zhangsan.setPet(tomcatPet());
return zhangsan;
}
@Bean("tom22")
public Pet tomcatPet(){
return new Pet("tomcat");
}
}
public static void main(String[] args) {
//1、返回我们IOC容器
ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
//2、查看容器里面的组件
String[] names = run.getBeanDefinitionNames();
for (String name : names) {
System.out.println(name);
}
boolean tom = run.containsBean("tom");
System.out.println("容器中Tom组件:"+tom);//false
boolean user01 = run.containsBean("user01");
System.out.println("容器中user01组件:"+user01);//true
boolean tom22 = run.containsBean("tom22");
System.out.println("容器中tom22组件:"+tom22);//true
}
底层注解-@ImportResource导入Spring配置文件
比如,公司使用bean.xml文件生成配置bean,然而你为了省事,想继续复用bean.xml,@ImportResource粉墨登场。
bean.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="hehe" class="com.peihj.pojo.pet">
<property name="name" value="tomcat001"/>
</bean>
<bean id="haha" class="com.peihj.pojo.User">
<property name="name" value="peihj"/>
<property name="age" value="18"/>
<property name="pet" ref="hehe"/>
</bean>
</beans>
使用方法:
@ImportResource("classpath:beans.xml")
public class MyConfig {
...
}
测试类:
public static void main(String[] args) {
//1、返回我们IOC容器
ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
boolean haha = run.containsBean("haha");
boolean hehe = run.containsBean("hehe");
System.out.println("haha:"+haha);//true
System.out.println("hehe:"+hehe);//true
}
底层注解-@ConfigurationProperties配置绑定
如何使用Java读取到properties文件中的内容,并且把它封装到JavaBean中,以供随时使用
传统方法:
public class getProperties {
public static void main(String[] args) throws FileNotFoundException, IOException {
Properties pps = new Properties();
pps.load(new FileInputStream("a.properties"));
Enumeration enum1 = pps.propertyNames();//得到配置文件的名字
while(enum1.hasMoreElements()) {
String strKey = (String) enum1.nextElement();
String strValue = pps.getProperty(strKey);
System.out.println(strKey + "=" + strValue);
//封装到JavaBean。
}
}
}
Spring Boot一种配置配置绑定:
@ConfigurationProperties + @Component
假设有配置文件application.properties
mycar.brand=BYD
mycar.price=100000
只有在容器中的组件,才会拥有SpringBoot提供的强大功能
@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {
...
}
Spring Boot另一种配置配置绑定:
@EnableConfigurationProperties + @ConfigurationProperties
- 开启Car配置绑定功能
- 把这个Car这个组件自动注册到容器中
@EnableConfigurationProperties(Car.class)
public class MyConfig {
...
}
@ConfigurationProperties(prefix = "mycar")
public class Car {
...
}
参考
尚硅谷
https://www.bilibili.com/video/BV19K4y1L7MT?p=13&t=9.5