Properties:
WebMvcProperties
类中,有一个@ConfigurationProperties
的注解,其中,prefix其对应的值就为配置文件中的前缀spring.mvc
,我们就可以找到我们配置的东西在何处映射到程序中了.xxxAutoConfiguration
类,它与之前的xxxproperties
类相对应,其目的就是为了加载xxxproperties
.常用的web中所需的静态资源,被webjars包所收录,可引入相应的依赖以此来导入web静态资源
可去官网查询相应的资源(如,JQuery、Bootstrap等等)
META_INF.resources.webjars.boostrap.4.5.0
,而其中由于META-INF/resources下的包会被SpringBoot默认扫描到,因此在访问资源时,可直接访问:/webjars/bootstrap/4.5.0/*
即可访问并使用Bootstrap资源。
- /META-INF/resources/ :webjars
- classpath:/resources/
- classpath:/static/
- classpath:/public/
这个顺序代表了优先级,再访问静态资源时,依次访问,如访问到,便返回结果
这里来做一个测试 如下图所示,每个1.js文件写着不同的内容,我们直接访问,看它们谁先展示出来
最后得出=> 1、2、3号位置的静态资源可访问且优先级为:resource > static > public
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//这里必须定制首页,因此访问templates下的页面必须走视图控制器
registry.addViewController("/").setViewName("index2");
registry.addViewController("index2.html").setViewName("index2");
}
}
只需要在resources目录下添加一下Banner.txt文件便可以了,里面的图案就是在SpringBoot启动时会打印的图案.
很有趣,有莫有.
当然了想要的DIY可不止于此.
除了一个文本文件,你还可以添加一个banner.gif
,banner.jpg
或banner.png
图像文件到类路径或设置spring.banner.image.location
属性。图像将转换为ASCII艺术作品并打印在任何文本横幅上方。
如果你对横幅没有什么要求,可以在自己创建的Application中关掉横幅.
自行实例化Application
public static void main(String[] args) {
SpringApplication app = new SpringApplication(MySpringConfiguration.class);
app.setBannerMode(Banner.Mode.OFF);
app.run(args);
}
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
public class MyLocaleResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest httpServletRequest) {
String language = httpServletRequest.getParameter("language");
Locale locale = Locale.getDefault();
if (!StringUtils.isEmpty(language)){
String[] split = language.split("_");
locale = new Locale(split[0], split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//这里必须定制首页,因此访问templates下的页面必须走视图控制器
registry.addViewController("/").setViewName("index2");
registry.addViewController("index2.html").setViewName("index2");
}
//添加自定义区域解析器到Spring容器
//返回类型为LocaleResolver,而不为MyLocaleResolver
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
}
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首页title>
<link th:href="@{css/bootstrap.min.css}" rel="stylesheet">
<link th:href="@{css/signin.css}" rel="stylesheet">
head>
<body>
<div class="container">
<form class="form-signin">
<h2 class="form-signin-heading" th:text="#{index.title}">请登录h2>
<label for="inputEmail" class="sr-only">Email addresslabel>
<input type="username" id="inputEmail" class="form-control" placeholder="用户名" th:placeholder="#{index.username}" required="" autofocus="">
<label for="inputPassword" class="sr-only" >Passwordlabel>
<input type="password" id="inputPassword" class="form-control" placeholder="密码" th:placeholder="#{index.password}" required="">
<div class="checkbox">
<label >
<input type="checkbox" value="remember-me" th:text="#{index.rememberMe}">
label>
div>
<button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{index.loginBtn}">Sign inbutton>
<p class="mt-5 mb-3 text-muted">@ 2017-2020p>
<a th:href="@{/index2.html(language='zh_CN')}" class="btn btn-sm">中文a>
<a th:href="@{/index2.html(language='en_US')}" class="btn btn-sm">Englisha>
form>
div>
body>
<script th:src="@{/js/jquery-3.2.1.slim.min.js}">script>
<script th:src="@{js/bootstrap.min.js}">script>
<script>
//Ajax请求
script>
html>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.19version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-jdbcartifactId>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.23version>
dependency>
spring:
datasource:
# 配置JDBC
url: jdbc:mysql://localhost:3306/my_train?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: PQS2017214206
type: com.alibaba.druid.pool.DruidDataSource
# 数据源其他配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000 #最小可撤离时间
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
# 配置监控统计拦截的filters,stat去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
ServletRegistrationBean
类与FilterRegistrationBean
类相当于web.xml里面配置Servlet与Filter@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDatasource(){
// System.out.println( "druid实例化");
return new DruidDataSource();
}
// 后台监控
@Bean
public ServletRegistrationBean servletRegistrationBean(){
ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");
Map<String, String> initParameters = new HashMap<String, String>();
initParameters.put("loginUserName","admin"); //登录名
initParameters.put("loginPassword","123"); //登录密码
initParameters.put("allow","127.0.0.1"); // "":所有人可访问 "localhost":本地可访问
bean.setInitParameters(initParameters);
return bean;
}
/**
* 配置服务过滤器
*
* @return 返回过滤器配置对象
*/
@Bean
public FilterRegistrationBean statFilter() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
// 添加过滤规则
filterRegistrationBean.addUrlPatterns("/*");
// 忽略过滤格式
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*,");
return filterRegistrationBean;
}
}
Note: 运行Mapper,需要配置好数据源之后的操作
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>2.1.3version>
dependency>
@Mapper //也可以在启动类上加@MapperScan注解
@Repository
public interface UserMapper {
List<User> selectAllUser();
User selectUserById(int id);
Integer updateUser(User user);
Integer insertUser(User user);
int deleteUser(int id);
}
<mapper namespace="com.gu_ppy.springbootstudy.mapper.UserMapper">
<select id="selectAllUser" resultType="user">
select * from user
select>
<select id="selectUserById" resultType="user">
select * from user where id=#{id}
select>
<update id="updateUser" parameterType="user">
update user set name = #{name},
age = #{age},
password = #{password}
where id=#{id}
update>
<insert id="insertUser" parameterType="user">
insert into user(name,age,password) values (#{name},#{age},#{password})
insert>
<delete id="deleteUser" >
delete from user where id=#{id}
delete>
mapper>
注意:xml文件很有可能忘记在yml文件中配置,不配置,在调用时mapper时,会显示
BindingException
异常,所以请务必加上配置.
# 配置Mybatis
mybatis:
type-aliases-package: com\skylan\tuantuan\pojo\entity
mapper-locations: classpath:mybatis/mapper/*.xml
configuration:
map-underscore-to-camel-case: true #开启驼峰式命名
@SpringBootTest
class SpringbootStudyApplicationTests {
@Autowired
UserMapper userMapper;
@Test
public void test(){
List<User> users = userMapper.selectAllUser();
for (User user : users) {
System.out.println(user);
}
}
@Test
public void test1(){
System.out.println(userMapper.selectUserById(1));
}
@Test
public void test2(){
userMapper.insertUser(new User(4,"尼马","33","222"));
test();
}
}
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-securityartifactId>
dependency>
2.0.9
.WebSecurityConfigurerAdapter
类中的注释。@EnableWebSecurity //必须注明为 启用web安全配置
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
http.formLogin();
//登出时处理路径和成功后跳转界面//登出时删除Cookie及Session
http.logout().logoutUrl("/logout").logoutSuccessUrl("/index").deleteCookies("").invalidateHttpSession(true);
http.csrf().disable();//关闭跨站请求防伪
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//在Security5中必须硬编码密码
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("root").password(new BCryptPasswordEncoder().encode("123")).roles("vip2","vip3")
.and()
.withUser("vip1").password(new BCryptPasswordEncoder().encode("123")).roles("vip2");
}
}
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//在Security5中必须硬编码密码,否则抛出异常
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("root").password(new BCryptPasswordEncoder().encode("123")).roles("vip2","vip3")
.and()
.withUser("vip1").password(new BCryptPasswordEncoder().encode("123")).roles("vip2");
}
}
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger2artifactId>
<version>2.9.2version>
dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger-uiartifactId>
<version>2.9.2version>
dependency>
@Configuration
@EnableSwagger2 //开启swagger,3.0版本配置不为这个
public class SwaggerConfig {
@Bean//生成Swagger的Docket实例
public Docket docket(Environment environment){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
}
}
package com.gu_ppy.springboot02security.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
@Configuration
@EnableSwagger2 //开启swagger,3.0版本配置不为这个
public class SwaggerConfig {
@Bean//生成Swagger的Docket实例
public Docket docket(Environment environment){
//设置启用swagger的环境
Profiles profiles = Profiles.of("dev","test");
//从环境中查找是否处于上诉环境
boolean isdev = environment.acceptsProfiles(profiles);
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.enable(isdev)//是否启用
//select...build是一套操作,不能分割
.select()
.apis(RequestHandlerSelectors.basePackage("com.gu_ppy.springboot02security.controller"))
.paths(PathSelectors.ant(""))//过滤一些接口
.build();
}
//配置API信息
@Bean
ApiInfo apiInfo(){
//作者信息
Contact contact = new Contact("Pixcer","http://www.smileboy.club","[email protected]");
return new ApiInfo("团团网API文档",
"SkyLan 天空之岚",
"0.1",
"http://www.smileboy.club",//组织名字
contact,
"Apache 2.0",//开源版本
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList());
}
}
spring:
profiles:
active: dev #配置环境dev,在项目部署时,修改其环境
@Configuration
@EnableSwagger2 //开启swagger
public class SwaggerConfig {
@Bean
public Docket docket1(){
return new Docket(DocumentationType.SWAGGER_2).groupName("小明");
}
@Bean
public Docket docket2(){
return new Docket(DocumentationType.SWAGGER_2).groupName("小张");
}
// More Docket Instance...
}
//或@Api("注释")
@ApiModel("订单类")
public class Order {
//修饰符为private会被忽略
@ApiModelProperty("订单ID")
public String orderId;
@ApiModelProperty("订单创建时间")
public Date OrderCreateTime;
@ApiModelProperty("订单状态")
public String OrderStatus;
}
@GetMapping("/getUser")
public Order getUser() {
return new Order();//返回一个实体类,则在swaggermodel上会显示该Api
}
@ApiOperation
:注释方法名/注释请求@ApiParam
:注释参数 @ApiOperation("获取订单信息")
@GetMapping("/getUser")
public Order getUser(@ApiParam("订单名") String name) {
return new Order();//返回一个实体类,则在swaggermodel上会显示该Api
}
ApiImplicitParams
:多个参数详解@ApiOperation(value = "审核商品",notes = "审核商品信息")
@PutMapping("/review")
@ApiImplicitParams({
@ApiImplicitParam(name = "id",value="商品ID",paramType = "form",required = true),
@ApiImplicitParam(name = "review",value="商品审核字段 传入0为未通过 1为通过",paramType = "form",required = true)
})
public R<Object> review(@RequestParam("id") Integer id,@RequestParam("review") Integer review){
goodsService.review(id,review);
return new R<>("商品已通过审核");
}
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-mailartifactId>
dependency>
spring:
#配置邮件
mail:
username: [email protected]
password: wxbbtpniitebe
protocol: smtp
properties: # QQ邮箱的加密
mail:
smtp:
ssl:
enable: true
host: smtp.qq.com
default-encoding: utf-8
@EableAsync
注解@Autowired
JavaMailSenderImpl mailSender;
@Async
public void SendEmail(){
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("[email protected]");//setFrom不能乱设置,必须为邮箱格式
message.setSubject("警告⚠");
//1302
message.setTo("[email protected]");
message.setText("你已被通缉!请联系我给你解除封锁.");
mailSender.send(message);
}
@Autowired
JavaMailSenderImpl mailSender;
@Async
public void SendMimeEmail() throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
//通过Helper的重载构造器来配置相应参数
MimeMessageHelper helper = new MimeMessageHelper(message,true);
helper.setSubject("666666");
helper.setText("皮亚二,原来是你!
",true);
//添加附件
helper.addAttachment("1.png",new File("C:\\Users\\gu-ppy\\Pictures\\portrait.png"));
helper.setTo("[email protected]");
helper.setFrom("[email protected]");
mailSender.send(message);
}
@Async : 此注解用于标注方法异步执行
@EnableAsync : 用于开启异步注解
@Scheduled : 标注定时任务,可用cron表达式描述时间
@EnableScheduling : 开启定时任务注解
@Scheduled(cron="30 10 10 * * ?")
:表示每天十点十分三十秒执行该定时任务@Scheduled(cron="30 10 10 ? * 1-6")
:表示每个星期一到星期六的十点十分三十秒执行@Scheduled(cron="0/30 * * * * ?")
:每隔三十秒执行一次
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<scope>runtimescope>
<optional>trueoptional>
dependency>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
<configuration>
<fork>truefork>
<addResources>trueaddResources>
configuration>
plugin>
下面两种配置方式选一种即可
# 热部署开关,false即不启用热部署
spring.devtools.restart.enabled: true
# 指定热部署的目录
#spring.devtools.restart.additional-paths: src/main/java
# 指定目录不更新
spring.devtools.restart.exclude: test/**
#配置热部署
devtools:
restart:
enabled: true
exclude: test/**
如果是idea,需要改以下两个地方:
1、勾上自动编译或者手动重新编译
File > Settings > Build, Execution, Deployment > Compiler-Build Project automatically
2、注册
factId>spring-boot-devtools
runtime
true
- 添加插件
```xml
org.springframework.boot
spring-boot-maven-plugin
true
true
下面两种配置方式选一种即可
# 热部署开关,false即不启用热部署
spring.devtools.restart.enabled: true
# 指定热部署的目录
#spring.devtools.restart.additional-paths: src/main/java
# 指定目录不更新
spring.devtools.restart.exclude: test/**
#配置热部署
devtools:
restart:
enabled: true
exclude: test/**
如果是idea,需要改以下两个地方:
1、勾上自动编译或者手动重新编译
File > Settings > Build, Execution, Deployment > Compiler-Build Project automatically
2、注册
ctrl + shift + alt + / > Registry > 勾选Compiler autoMake allow when app running