SpringBoot自动配置了SpringMVC组件,而Web开发场景在SpringBoot应用十分常用。
静态资源原理SpringBoot默认静态资源可以从以下路径中获取:/static (or /public or /resources or /meta-INF/resources)。由于SpringBoot启动默认加载SpringMVC功能的自动配置类 WebMvcAutoConfiguration
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,
ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {}
而配置文件的相关属性和xxx进行了绑定。WebMvcProperties==spring.mvc、ResourceProperties==spring.resources
@Configuration(proxyBeanMethods = false)
@import(EnableWebMvcConfiguration.class)
@EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class })
@Order(0)
public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer {}
@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties {
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/meta-INF/resources/",
"classpath:/resources/", "classpath:/static/", "classpath:/public/" };
private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
所以我们可以在application.yml文件中修改相关的mvc配置:
spring:
application:
name: demo
resources:
static-locations: [classpath:/res/] #修改静态资源路径
mvc:
contentnegotiation:
favor-parameter: true #开启favicon.ico
此配置类只有一个有参构造方法,相关参数直接从Spring容器中获取:
//有参构造器所有参数的值都会从容器中确定
//ResourceProperties resourceProperties;获取和spring.resources绑定的所有的值的对象
//WebMvcProperties mvcProperties 获取和spring.mvc绑定的所有的值的对象
//ListableBeanFactory beanFactory Spring的beanFactory
//HttpMessageConverters 找到所有的HttpMessageConverters
//ResourceHandlerRegistrationCustomizer 找到 资源处理器的自定义器。=========
//DispatcherServletPath
//ServletRegistrationBean 给应用注册Servlet、Filter....
public WebMvcAutoConfigurationAdapter(ResourceProperties resourceProperties, WebMvcProperties mvcProperties,
ListableBeanFactory beanFactory, ObjectProvider messageConvertersProvider,
ObjectProvider resourceHandlerRegistrationCustomizerProvider,
ObjectProvider dispatcherServletPath,
ObjectProvider> servletRegistrations) {
this.resourceProperties = resourceProperties;
this.mvcProperties = mvcProperties;
this.beanFactory = beanFactory;
this.messageConvertersProvider = messageConvertersProvider;
this.resourceHandlerRegistrationCustomizer = resourceHandlerRegistrationCustomizerProvider.getIfAvailable();
this.dispatcherServletPath = dispatcherServletPath;
this.servletRegistrations = servletRegistrations;
}
- 资源处理规则
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
return;
}
Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
//webjars的规则
if (!registry.hasMappingForPattern("/webjars
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("开始登录检查:{}", request.getRequestURI());
//登录检查
Object account = request.getSession().getAttribute("account");
if (account != null) {
return true;
}
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
由于每个请求都会经过DispatchServlet处理器,所以需要将自定义的拦截器注册到Spring容器中才能生效
@Configuration
public class MyConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor()).
addPathPatterns("/user
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public void upload(@RequestParam("files") MultipartFile[] files) {
System.out.println("文件个数:"+files.length);
try {
for (MultipartFile file : files) {
if (!file.isEmpty()) {
String filename = file.getOriginalFilename();
file.transferTo(new File("F:\images\" + filename));
}
}
} catch (IOException e) {
System.out.println("文件上传失败");
}
}
数据访问
SpringBoot在数据访问也封装了对应的Starter,首先导入相关依赖
com.alibaba
druid-spring-boot-starter
1.1.13
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.1.4
mysql
mysql-connector-java
5.1.47
SpringBoot的自动装配为我们做了以下准备工作:
● 底层将默认的数据源替换为阿里的Druid数据源
● SqlSessionFactory: 自动配置好了
● SqlSession:自动配置了 SqlSessionTemplate 组合了SqlSession
● @import(AutoConfiguredMapperScannerRegistrar.class);
● Mapper: 只要我们写的操作MyBatis的接口标准了 @Mapper 就会被自动扫描进来
@Configuration
@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
@ConditionalOnBean({DataSource.class})
@EnableConfigurationProperties({MybatisProperties.class})
@AutoConfigureAfter({DataSourceAutoConfiguration.class})
public class MybatisAutoConfiguration {}
//配置项
@ConfigurationProperties(
prefix = "mybatis"
)
public class MybatisProperties {}
配置信息yml:
#数据源
spring:
datasource:
url: jdbc:mysql://localhost:3306/xf_test?characterEncoding=utf-8&useSSL=false
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
#mybatis配置
mybatis:
mapper-locations: classpath:mapper/*.xml
configuration:
map-underscore-to-camel-case: true
Profile功能
为了方便多环境适配,springboot简化了profile功能。
● 默认配置文件 application.yaml;任何时候都会加载
● 指定环境配置文件 application-{env}.yaml
● 激活指定环境
○ 配置文件激活
○ 命令行激活:java -jar xxx.jar --spring.profiles.active=prod
■ 修改配置文件的任意值,命令行优先
● 默认配置与环境配置同时生效
● 同名配置项,profile配置优先
这样整个程序的配置就很方便切换到prod环境,未来在微服务架构中,借助其他配置中心比如Nacos来管理多环境的配置信息,也比较常用
以上就是SpringBoot中部分十分常用并且重要的技术



