SpringBoot的依赖管理和底层注解,还有样例:自定义的视图解析器
一:SpringBoot的特点
一:依赖管理
1.父项目做依赖管理:
springboot可以选择继承父项目的jar包,例:
依赖管理 <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>几乎声明了所有开发中常用的依赖的版本号,自动版本仲裁机制
2.修改父项目中的依赖的版本号:
例:修改mysql的版本,将父项目中mysql8.0.21的版本改为5.1.42
<properties> <mysql.version>5.1.42</mysql.version> </properties>
3.springboot无需关注版本号,自动版本仲裁
(1)引入依赖不写版本号的原因是因为spring-boot-dependencies有默认的版本号
(2)引入的非版本仲裁的包,是需要自己写的。
2.自动配置
-
自动配置号web常见功能:如:字符编码问题
拦截所有请求:dispatcherServlet
字符乱码问题:characterEncodingFilter(字符编码拦截器) -
配置默认包结构
主程序所在包及其下面的所有子包里面的组件都会被默认扫描进来
想要改变扫描路径:@SpringBootApplication(scanBasePackages = "com.example")
或者使用@ComponentSacn指定扫描路径 -
各种配置都有默认值
springboot所有的自动配置功能都在spring-boot-autoconfigure
4.默认的包结构
主程序所在包机器下面的所有子包里面的组件会被默认扫描进来
如果想要改变包的位置,使用 @SpringBootApplication(scanBasePackages = “com.example.springboot”)
更改springboot包扫的位置或者使用@ComponentScan指定扫描路径
@SpringBootApplication()等同于@SpringBootConfiguration@EnableAutoConfiguration@ComponentScan("com.example.springboot")
5.springboot按需加载配置项
springboot素有的自动配置功能都在
<groupId>org.springframework.boot</groupId> <artifactId>spring-boot-autoconfigure</artifactId>包下
二:底层注解
1.@Configuration注解
@Configuration(proxyBeanMethods = true) //告诉springboot这是一个配置类 == 配置文件
/ * 1.配置类里面使用@Bean标注方法上给容器注册组件,默认也是单实例的 * 2.配置类也是组件 * 3.proxyBeanMethods:代理bean的方法 * Full(proxyBeanMethods = true)、【保证每个@Bean方法被调用多少次返回的组件都是单实例的】 * Lite(proxyBeanMethods = false)【每个@Bean方法被调用多少次返回的组件都是新创建的】 * 组件依赖必须使用Full模式默认。其他默认是否Lite模式 */@Configuration(proxyBeanMethods = true) //告诉springboot这是一个配置类 == 配置文件public class MyConfig { / * 外部无论对配置类中的这个组件注册方法掉哦那个多少次都是之前注册容器中的单实例对象 * */ @Bean //给容器中添加组件,以方法名作为组件的id,返回类型就是组件类型,返回的值,就是组件在容器的实例 public User user01(){ return new User("zhangsasn",18); }// 自定义组件名 @Bean("wang") public Pet tomcatPet(){ return new Pet("tomcat"); }}
2.@Import注解
@Import({User.class, DBHelper.class}) 给容器中自动创建出这两个类型的组件、默认组件的名字就是全类名
3.@override
@Override注解的作用用以标明这是你在子类中重写父类的方法,编译器可以自动帮你验证@Override下面的方法名称是否是你父类中所有的,如果没有就会报错。
三.:样例使用@configuration添加配置,自定义视图解析器
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.View;import org.springframework.web.servlet.ViewResolver;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;import java.util.Locale;//自定义视图解析器//定制功能,在config中写一个组件,将他交给springboot,springboot就会帮我们自动装配!//扩展springmvc@Configurationpublic class MyMvcConfig implements WebMvcConfigurer {// 手动接管视图解析器// ViewResolver 实现了视图解析器接口的类,我们就可以把它看作视图解析器 @Bean public ViewResolver myViewResolver(){ return new MyViewResolver(); } // 自定义了一个自己的视图解析器MyViewResolver public static class MyViewResolver implements ViewResolver { @Override public View resolveViewName(String viewName, Locale locale){ return null; } }}