提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
一些关于springBoot得学习过程记录,还是菜鸟阶段,主要还是在模仿,可能在这个过程中缺少一些自己得思考,如果有不对得地方还请大佬多多批评指正!!这里就当作是记录笔记得地方
提示:以下是本篇文章正文内容,下面案例可供参考
springboot2
一、创建一个新项目
1.通过idea创建:
- 目录结构:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-a1Wd6zL4-1622160780066)(springboot.assets/image-20210429200453224.png)]
-
第一个程序
package com.warrior.boothello.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController//相当于@controller + @responseBody public class helloController { @RequestMapping("/hello") public String hello(){ //调用业务、接收前端参数 return "hello world"; } }
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1XFVfUV1-1622160780068)(springboot.assets/image-20210429200644658.png)]
-
想到的一些问题
-
springboot中的web.xml配置方式不见了
servlet3.0规范中,可以通过java配置(注解等)代替web.xml,spring boot就是使用java代替了web.xml。
其中javax.servlet.ServletContainerInitializer负责web容器启动阶段被回调,在onStartup方法里注册servlet、filter、listener等。
spring web包实现了这个类。
-
二、自动装配原理
-
结论:
springboot的所有自动配置都是在启动的时候扫描并加载:spring.factories所有的自动配置类都在这里面,但是不一定生效,要判断条件是否成立,只要导入了对应的start,就有对应的启动器,有了启动器,我们的自动配置就会生效,然后就配置成功
-
流程:
①spring在启动的时候,从类路径/META-INF/spring.factories获取指定的值;
②将这些自动配置的类导入容器,自动配置生效,进行自动配置
③整个JavaEE,解决方案和自动配置的东西都在spring-boot-autoconfiguration-2.2.0.RELEASE.jar包下
④他会把所有需要导入的组件,以类名的方式返回,这些组件就会被添加到容器当中
⑤文件中存在许多的XXXAutoConfiguration的文件(@Bean),这些类给容器中导入某些场景下需要的组件,并自动配置@Configuration
⑥有了自动配置类,免去了手动配置文件的书写
-
SpringApplication
@SpringBootApplication public class SpringbootApplication { public static void main(String[] args) { SpringApplication.run(SpringbootApplication.class, args); }}
1、推断应用的类型是普通的项目还是Web项目
2、查找并加载所有可用初始化器 , 设置到initializers属性中
3、找出所有的应用程序监听器,设置到listeners属性中
4、推断并设置main方法的定义类,找到运行的主类
-
自动配置原理
1.举例:
//表示这是一个配置类,和以前编写的配置文件一样,也可以给容器中添加组件; @Configuration //启动指定类的ConfigurationProperties功能; //进入这个HttpProperties查看,将配置文件中对应的值和HttpProperties绑定起来; //并把HttpProperties加入到ioc容器中 @EnableConfigurationProperties({HttpProperties.class}) //Spring底层@Conditional注解 //根据不同的条件判断,如果满足指定的条件,整个配置类里面的配置就会生效; //这里的意思就是判断当前应用是否是web应用,如果是,当前配置类生效 @ConditionalOnWebApplication( type = Type.SERVLET ) //判断当前项目有没有这个类CharacterEncodingFilter;SpringMVC中进行乱码解决的过滤器; @ConditionalOnClass({CharacterEncodingFilter.class}) //判断配置文件中是否存在某个配置:spring.http.encoding.enabled; //如果不存在,判断也是成立的 //即使我们配置文件中不配置pring.http.encoding.enabled=true,也是默认生效的; @ConditionalOnProperty( prefix = "spring.http.encoding", value = {"enabled"}, matchIfMissing = true ) public class HttpEncodingAutoConfiguration { //他已经和SpringBoot的配置文件映射了 private final Encoding properties; //只有一个有参构造器的情况下,参数的值就会从容器中拿 public HttpEncodingAutoConfiguration(HttpProperties properties) { this.properties = properties.getEncoding(); } //给容器中添加一个组件,这个组件的某些值需要从properties中获取 @Bean @ConditionalOnMissingBean //判断容器没有这个组件? public CharacterEncodingFilter characterEncodingFilter() { CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter(); filter.setEncoding(this.properties.getCharset().name()); filter.setForceRequestEncoding(this.properties.shouldForce(org.springframework.boot.autoconfigure.http.HttpProperties.Encoding.Type.REQUEST)); filter.setForceResponseEncoding(this.properties.shouldForce(org.springframework.boot.autoconfigure.http.HttpProperties.Encoding.Type.RESPONSE)); return filter; } //。。。。。。。 }
一句话总结 :根据当前不同的条件判断,决定这个配置类是否生效!
- 一但这个配置类生效;这个配置类就会给容器中添加各种组件;
- 这些组件的属性是从对应的properties类中获取的,这些类里面的每一个属性又是和配置文件绑定的;
- 所有在配置文件中能配置的属性都是在xxxxProperties类中封装着;
- 配置文件能配置什么就可以参照某个功能对应的这个属性类
//从配置文件中获取指定的值和bean的属性进行绑定 @ConfigurationProperties(prefix = "spring.http") public class HttpProperties { // ..... }
总结:
1、SpringBoot启动会加载大量的自动配置类
2、我们看我们需要的功能有没有在SpringBoot默认写好的自动配置类当中;
3、我们再来看这个自动配置类中到底配置了哪些组件;(只要我们要用的组件存在在其中,我们就不需要再手动配置了)
4、给容器中自动配置类添加组件的时候,会从properties类中获取某些属性。我们只需要在配置文件中指定这些属性的值即可;
**xxxxAutoConfigurartion:自动配置类;**给容器中添加组件
xxxxProperties:封装配置文件中相关属性;
-
@conditional
自动配置类需要在一定的条件下才能生效
@Conditional派生注解(Spring注解版原生的@Conditional作用)
作用:必须是@Conditional指定的条件成立,才给容器中添加组件,配置配里面的所有内容才生效;
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2ZjWjykO-1622160780069)(springboot.assets/image-20210505100226496.png)]
我们可以通过启用 debug=true属性;来让控制台打印自动配置报告,这样我们就可以很方便的知道哪些自动配置类生效;
#开启springboot的调试类 debug=true
Positive matches:(自动配置类启用的:正匹配)
Negative matches:(没有启动,没有匹配成功的自动配置类:负匹配)
Unconditional classes: (没有条件的类)
三、yaml语法讲解
-
语法格式:
# 普通键值对的语法 name: jack # 存一个对象 student: name: jack age: 18 # 行内写法: studen: {name: jack,age: 18} #数组: pets: - cat - dog - pig pets: [cat,dog,pig]
说明:语法要求严格!
1、空格不能省略
2、以缩进来控制层级关系,只要是左边对齐的一列数据都是同一个层级的。
3、属性和值的大小写都是十分敏感的。
-
多环境配置及文件的位置
-
配置文件的加载位置:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-B9b2cwhd-1622160780070)(springboot.assets/image-20210505091947581.png)]
-
优先级:
1:项目路径下的config文件夹配置文件优先级 2:项目路径下配置文件优先级 3:资源路径下的config文件夹配置文件优先级 4:资源路径下配置文件
优先级由高到底,高优先级的配置会覆盖低优先级的配置;
SpringBoot会从这四个位置全部加载主配置文件;互补配置;
-
一些配置参数:
# REDIS (Redis 配置) # 连接工厂使用的数据库索引 spring.redis.database= 0 # Redis服务器主机 spring.redis.host= localhost # 登录redis服务器的密码 spring.redis.password= # 给定时间池可以分配的最大连接数 使用负值为无限制 spring.redis.pool.max-active= 8 # 池中“空闲”连接的最大数量 使用负值来表示无限数量的空闲连接 spring.redis.pool.max-idle= 8 # 连接分配在池耗尽之前在抛出异常之前应阻止的最大时间量(以毫秒为单位) 使用负值无限期地阻止 spring.redis.pool.max-wait= -1 # 定义池中维护的最小空闲连接数 此设置只有在正值时才有效果 spring.redis.pool.min-idle= 0 # redis服务器端口 spring.redis.port= 6379 # redis服务器名称 spring.redis.sentinel.master= # spring.redis.sentinel.nodes= # 连接超时(毫秒) spring.redis.timeout= 0 # spring 视图分解器 配置 # 启用后退解析支持 spring.mobile.devicedelegatingviewresolver.enable-fallback= false # 启用设备视图解析器 spring.mobile.devicedelegatingviewresolver.enabled= false # 前缀,用于查看移动设备的名称 spring.mobile.devicedelegatingviewresolver.mobile-prefix= mobile/ # 后缀,附加到查看移动设备的名称 spring.mobile.devicedelegatingviewresolver.mobile-suffix= # 前缀,用于查看普通设备的名称 spring.mobile.devicedelegatingviewresolver.normal-prefix= # 后缀,附加到查看普通设备的名称 spring.mobile.devicedelegatingviewresolver.normal-suffix= # 前缀,用于查看平板设备的名称 spring.mobile.devicedelegatingviewresolver.tablet-prefix= tablet/ # 后缀,附加到查看平板电脑设备的名称 spring.mobile.devicedelegatingviewresolver.tablet-suffix= # 移动网站首选项 (站点首选项自动配置) # 启用SitePreferenceHandler spring.mobile.sitepreference.enabled= true # MUSTACHE模板(Mustache AutoConfiguration) # 启用模板缓存 spring.mustache.cache= false # 模板编码 spring.mustache.charset= UTF-8 # 检查模板位置是否存在 spring.mustache.check-template-location= true # Content-Type值 spring.mustache.content-type= text/html # 启用此技术的MVC视图分辨率 spring.mustache.enabled= true # 前缀应用于模板名称 spring.mustache.prefix= classpath:/templates/ # 后缀应用于模板名称 spring.mustache.suffix= .html # 可以解决的视图名称的白名单 spring.mustache.view-names= # SPRING MVC (Web Mvc 配置) # 异步请求处理超时之前的时间量(以毫秒为单位) spring.mvc.async.request-timeout= # 要使用的日期格式 例如`dd / MM / yyyy` spring.mvc.date-format= # 发送TRACE请求到FrameworkServlet doService方法 spring.mvc.dispatch-trace-request= false # 发送OPTIONS请求到FrameworkServlet doService方法 spring.mvc.dispatch-options-request= false # 启用favicon.ico的解析 spring.mvc.favicon.enabled= true # 如果在重定向方案期间应该忽略“默认”模型的内容 spring.mvc.ignore-default-model-on-redirect= true # 要使用的区域设置 spring.mvc.locale= # 将文件扩展名映射到内容协商的媒体类型 spring.mvc.media-types.*= # 消息代码格式策略 例如`PREFIX_ERROR_CODE` spring.mvc.message-codes-resolver-format= # 用于静态资源的路径模式 spring.mvc.static-path-pattern= /** # 如果没有发现处理程序来处理请求,则应抛出“NoHandlerFoundException” spring.mvc.throw-exception-if-no-handler-found= false # Spring MVC视图前缀 spring.mvc.view.prefix= # Spring MVC视图后缀 spring.mvc.view.suffix= #SPRING RESOURCES HANDLING(ResourceProperties)资源处理 spring.resources.add-mappings = true #启用默认资源处理 spring.resources.cache-period = #由资源处理程序提供的资源的缓存期,以秒为单位 spring.resources.chain.cache = true #在资源链中启用缓存 spring.resources.chain.enabled = #启用Spring资源处理链默认情况下禁用,除非启用了至少一个策略 spring.resources.chain.html-application-cache = false #启用HTML5应用程序缓存清单重写 spring.resources.chain.strategy.content.enabled = false #启用内容版本策略 spring.resources.chain.strategy.content.paths = / ** #应用于版本策略的模式的逗号分隔列表 spring.resources.chain.strategy.fixed.enabled = false #启用固定版本策略 spring.resources.chain.strategy.fixed.paths = #应用于版本策略的逗号分隔的模式列表 spring.resources.chain.strategy.fixed.version = #用于版本策略的版本字符串 spring.resources.static-locations = classpath:/ META-INF / resources /,classpath:/ resources /,classpath:/ static /,classpath:/ public / #静态资源的位置 #SPRING SOCIAL(SocialWebAutoConfiguration)集群 spring.social.auto-connection-views = false #启用支持的提供程序的连接状态视图 #SPRING SOCIAL FACEBOOK(FacebookAutoConfiguration) spring.social.facebook.app-id = #您的应用程序的Facebook应用程序ID spring.social.facebook.app-secret = #你的应用程序的Facebook应用程序密码 #SPRING SOCIAL LINKEDIN(LinkedInAutoConfiguration) spring.social.linkedin.app-id = #您的应用程序的LinkedIn应用程序ID spring.social.linkedin.app-secret = #您的应用程序的LinkedIn App Secret #SPRING SOCIAL TWITTER(TwitterAutoConfiguration) spring.social.twitter.app-id = #你的应用程序的Twitter应用程序ID spring.social.twitter.app-secret = #你的应用程序的Twitter App Secret #THYMELEAF Thymeleaf模板引擎配置 spring.thymeleaf.cache = true #启用模板缓存 spring.thymeleaf.check-template-location = true #检查模板位置是否存在 spring.thymeleaf.content-type = text / html #Content-Type值 spring.thymeleaf.enabled = true #启用MVC Thymeleaf视图分辨率 spring.thymeleaf.encoding = UTF-8 #模板编码 spring.thymeleaf.excluded-view-names = #应该从解决方案中排除的视图名称的逗号分隔列表 spring.thymeleaf.mode = HTML5 #应用于模板的模板模式另请参见StandardTemplateModeHandlers spring.thymeleaf.prefix = classpath:/ templates / #在构建URL时预先查看名称的前缀 spring.thymeleaf.suffix = .html #构建URL时附加查看名称的后缀 spring.thymeleaf.template-resolver-order = #链中模板解析器的顺序 spring.thymeleaf.view-names = #可以解析的视图名称的逗号分隔列表 #VELOCITY TEMPLATES(VelocityAutoConfiguration) spring.velocity.allow-request-override = false #设置是否允许HttpServletRequest属性覆盖(隐藏)控制器生成的同名的模型属性 spring.velocity.allow-session-override = false #设置是否允许HttpSession属性重写(隐藏)控制器生成的同名的模型属性 spring.velocity.cache = #启用模板缓存 spring.velocity.charset = UTF-8 #模板编码 spring.velocity.check-template-location = true #检查模板位置是否存在 spring.velocity.content-type = text / html #Content-Type值 spring.velocity.date-tool-attribute = #在视图的Velocity上下文中公开的DateTool辅助对象的名称 spring.velocity.enabled = true #启用此技术的MVC视图分辨率 spring.velocity.expose-request-attributes = false #设置在与模板合并之前是否应将所有请求属性添加到模型中 spring.velocity.expose-session-attributes = false #设置在与模板合并之前是否应将所有HttpSession属性添加到模型中 spring.velocity.expose-spring-macro-helpers = true #设置是否公开一个RequestContext供Spring Spring的宏库使用,名称为“springMacroRequestContext” spring.velocity.number-tool-attribute = #在视图的Velocity上下文中公开的NumberTool帮助对象的名称 spring.velocity.prefer-file-system-access = true #首选文件系统访问模板加载文件系统访问可以对模板更改进行热检测 spring.velocity.prefix = #前缀,用于在构建URL时查看名称 spring.velocity.properties* = #附加速度属性 spring.velocity.request-context-attribute = #所有视图的RequestContext属性的名称 spring.velocity.resource-loader-path = classpath:/ templates / #模板路径 spring.velocity.suffix = .vm #构建URL时附加到查看名称的后缀 spring.velocity.toolbox-config-location = #Velocity Toolbox配置位置例如`/ WEB-INF / toolbox.xml' spring.velocity.view-names = #可以解决的视图名称的白名单 #---------------------------------------- #安全属性 #---------------------------------------- #SECURITY(SecurityProperties) security.basic.authorize-mode = role #应用安全授权模式 security.basic.enabled = true #启用基本身份验证 security.basic.path = / ** #安全路径的逗号分隔列表 security.basic.realm = Spring #HTTP基本的领域名称 security.enable-csrf = false #启用跨站点请求伪造支持 security.filter-order = 0 #安全过滤器连锁订单 security.headers.cache = true #启用缓存控制HTTP头 security.headers.content-type = true# 启用“X-Content-Type-Options”头 security.headers.frame = true #启用“X-Frame-Options”标题 security.headers.hsts = # HTTP严格传输安全(HSTS)模式(无,域,全部) security.headers.xss = true #启用跨站点脚本(XSS)保护 security.ignored = #从默认安全路径中排除的路径的逗号分隔列表 security.require-ssl = false #为所有请求启用安全通道 security.sessions = stateless #会话创建策略(永远不会,if_required,无状态) security.user.name = user #默认用户名 security.user.password = #默认用户名的密码默认情况下,启动时会记录随机密码 security.user.role = USER #为默认用户名授予角色 #SECURITY OAUTH2 CLIENT(OAuth2ClientProperties security.oauth2.client.client-id = #OAuth2客户端ID security.oauth2.client.client-secret = #OAuth2客户机密码默认生成随机密码 #SECURITY OAUTH2 RESOURCES(ResourceServerProperties security.oauth2.resource.id = #资源的标识符 security.oauth2.resource.jwt.key-uri = #JWT令牌的URI如果值不可用并且密钥是公共的,可以设置 security.oauth2.resource.jwt.key-value = #JWT令牌的验证密钥可以是对称秘密或PEM编码的RSA公钥 security.oauth2.resource.prefer-token-info = true #使用令牌信息,可以设置为false以使用用户信息 security.oauth2.resource.service-id = resource # security.oauth2.resource.token-info-uri = #令牌解码端点的URI security.oauth2.resource.token-type = #使用userInfoUri时发送的令牌类型 security.oauth2.resource.user-info-uri = #用户端点的URI #SECURITY OAUTH2 SSO(OAuth2SsoProperties security.oauth2.sso.filter-order = #如果不提供显式的WebSecurityConfigurerAdapter,则应用过滤器顺序 security.oauth2.sso.login-path = / login #登录页面的路径,即触发重定向到OAuth2授权服务器的路径 # ---------------------------------------- # DATA PROPERTIES 数据性能 # ---------------------------------------- # FLYWAY (FlywayProperties) flyway.baseline-description = # flyway.baseline-version = 1 #版本开始迁移 flyway.baseline-on-migrate = # flyway.check-location = false #检查迁移脚本位置是否存在 flyway.clean-on-validation-error = # flyway.enabled = true #启用飞行路线 flyway.encoding = # flyway.ignore-failed-future-migration = # flyway.init-sqls = #执行SQL语句,以便在获取连接后立即初始化连接 flyway.locations = classpath:db / migration #迁移脚本的位置 flyway.out-of-order = #如果您希望Flyway创建自己的DataSource,则需要使用#path密码 flyway.placeholder-prefix = # flyway.placeholder-replacement = # flyway.placeholder-suffix = # flyway.placeholders* = # flyway.schemas = #schemas来更新 flyway.sql-migration-prefix = V # flyway.sql-migration-separator = # flyway.sql-migration-suffix = .sql # flyway.table = # flyway.url = #要迁移的数据库的JDBC url如果未设置,则使用主配置的数据源 flyway.user = #登录要迁移的数据库的用户 flyway.validate-on-migrate = # # LIQUIBASE (LiquibaseProperties) liquibase.change-log = classpath:/db/changelog/db.changelog-master.yaml #更改日志配置路径 liquibase.check-change-log-location = true #检查更改日志位置是否存在 liquibase.contexts = #使用逗号分隔的运行时上下文列表 liquibase.default-schema = #默认数据库模式 liquibase.drop-first = false #首先删除数据库模式 liquibase.enabled = true #启用liquidibase支持 liquibase.labels = #使用逗号分隔的运行时标签列表 liquibase.parameters* = #更改日志参数 liquibase.password = #登录要迁移的数据库的密码 liquibase.url = #要迁移的数据库的JDBC url 如果未设置,则使用主配置的数据源 liquibase.user = #登录要迁移的数据库的用户 # DAO (PersistenceExceptionTranslationAutoConfiguration) spring.dao.exceptiontranslation.enabled= true # 启用持久异常翻译后处理器 # CASSANDRA (CassandraProperties) spring.data.cassandra.cluster-name = #Cassandra群集的名称 spring.data.cassandra.compression = #由Cassandra二进制协议支持的压缩 spring.data.cassandra.connect-timeout-millis = #套接字选项:连接超时 spring.data.cassandra.consistency-level = #查询一致性级别 spring.data.cassandra.contact-points = localhost #集群节点地址的逗号分隔列表 spring.data.cassandra.fetch-size = #查询默认的抓取大小 spring.data.cassandra.keyspace-name = #要使用的密钥空间名称 spring.data.cassandra.load-balancing-policy = #负载均衡策略的类名 spring.data.cassandra.port = #Cassandra服务器端口 spring.data.cassandra.password = #登录服务器的密码 spring.data.cassandra.read-timeout-millis = #套接字选项:读取超时 spring.data.cassandra.reconnection-policy = #重新连接策略类 spring.data.cassandra.retry-policy = #重试策略的类名 spring.data.cassandra.serial-consistency-level = #查询串行一致性级别 spring.data.cassandra.ssl = false #启用SSL支持 spring.data.cassandra.username = #登录用户的服务器 # ELASTICSEARCH (ElasticsearchProperties) spring.data.elasticsearch.cluster-name = elasticsearch #弹性搜索集群名称 spring.data.elasticsearch.cluster-nodes = #集群节点地址的逗号分隔列表 如果未指定,则启动客户端节点 spring.data.elasticsearch.properties* = #用于配置客户端的其他属性 spring.data.elasticsearch.repositories.enabled = true #启用Elasticsearch存储库 # MONGODB (MongoProperties) spring.data.mongodb.authentication-database = #验证数据库名称 spring.data.mongodb.database = test #数据库名称 spring.data.mongodb.field-naming-strategy = #要使用的FieldNamingStrategy的完全限定名称 spring.data.mongodb.grid-fs-database = #GridFS数据库名称 spring.data.mongodb.host = localhost #Mongo服务器主机 spring.data.mongodb.password = #登录mongo服务器的密码 spring.data.mongodb.port = 27017 #Mongo服务器端口 spring.data.mongodb.repositories.enabled = true #启用Mongo存储库 spring.data.mongodb.uri = mongodb:// localhost / test #Mongo数据库URI 设置时,主机和端口将被忽略 spring.data.mongodb.username = #登录mongo服务器的用户 # DATA REST (RepositoryRestProperties) spring.data.rest.base-path = #由Spring Data REST用于公开存储库资源的基本路径 spring.data.rest.default-page-size = #页面的默认大小 spring.data.rest.enable-enum-translation = #通过Spring Data REST默认资源包启用枚举值转换 spring.data.rest.limit-param-name = #指示一次返回多少结果的URL查询字符串参数的名称 spring.data.rest.max-page-size = #最大页面大小 spring.data.rest.page-param-name = #指示要返回的页面的URL查询字符串参数的名称 spring.data.rest.return-body-on-create = #创建一个实体后返回响应体 spring.data.rest.return-body-on-update = #更新实体后返回响应体 spring.data.rest.sort-param-name = #指示排序结果的方向的URL查询字符串参数的名称 # SOLR (SolrProperties) spring.data.solr.host = http://127.0.0.1:8983/solr #Solr主机 如果设置了“zk-host”,则被忽略 spring.data.solr.repositories.enabled = true #启用Solr存储库 spring.data.solr.zk-host = #ZooKeeper主机地址,格式为HOST:PORT # 数据源 配置 (DataSourceAutoConfiguration & DataSourceProperties) spring.datasource.continue-on-error = false #初始化数据库时发生错误时不要停止 spring.datasource.data = #Data(DML)脚本资源引用 spring.datasource.driver-class-name = #JDBC驱动程序的完全限定名称默认情况下,根据URL自动检测 spring.datasource.initialize = true #使用'data.sql'填充数据库 spring.datasource.jmx-enabled = false #启用JMX支持(如果由底层池提供) spring.datasource.jndi-name = #数据源的JNDI位置设置时,类,网址,用户名和密码将被忽略 spring.datasource.max-active = #例如100 spring.datasource.max-idle = #例如8 spring.datasource.max等待= spring.datasource.min-evictable空闲时间-米利斯= spring.datasource.min-idle = 8 spring.datasource.name = testdb #数据源的名称 spring.datasource.password = #登录数据库的密码 spring.datasource.platform = all #在资源模式(schema - $ {platform} .sql)中使用的平台 spring.datasource.schema = #Schema(DDL)脚本资源引用 spring.datasource.separator =; #语句分隔符在SQL初始化脚本中 spring.datasource.sql-script-encoding = #SQL脚本编码 spring.datasource.test-on-borrow = #例如`false` spring.datasource.test-on-return = #例如`false` spring.datasource.test-while-idle = # spring.datasource.time-between-eviction-runs-millis = 1 spring.datasource.type = #要使用的连接池实现的完全限定名称默认情况下,它是从类路径自动检测的 spring.datasource.url = #数据库的JDBC url spring.datasource.username= spring.datasource.validation-query= # H2 Web Console (H2ConsoleProperties) spring.h2.console.enabled = false #启用控制台 spring.h2.console.path = / h2-console #控制台可用的路径 # JOOQ (JooqAutoConfiguration) spring.jooq.sql-dialect= # 与配置的数据源通信时使用的SQLDialect JOOQ 例如`POSTGRES` # JPA (JpaBaseConfiguration, HibernateJpaAutoConfiguration) spring.data.jpa.repositories.enabled = true #启用JPA存储库 spring.jpa.database = #目标数据库进行操作,默认情况下自动检测可以使用“databasePlatform”属性设置 spring.jpa.database-platform = #要运行的目标数据库的名称,默认情况下自动检测可以使用“数据库”枚举来设置 spring.jpa.generate-ddl = false #启动时初始化模式 spring.jpa.hibernate.ddl-auto = #DDL模式这实际上是“hibernate.hbm2ddl.auto”属性的快捷方式使用嵌入式数据库时默认为“创建删除”,否则为“否” spring.jpa.hibernate.naming-strategy = #命名策略完全限定名 spring.jpa.open-in-view = true #注册OpenEntityManagerInViewInterceptor将JPA EntityManager绑定到线程以进行请求的整个处理 spring.jpa.properties* = #在JPA提供程序上设置的其他本机属性 spring.jpa.show-sql = false #启用SQL语句的日志记录 # JTA (JtaAutoConfiguration) spring.jta* = #技术特定配置 spring.jta.log-dir = #Transaction logs目录 # ATOMIKOS spring.jta.atomikos.connectionfactory.borrow-connection-timeout = 30 #从池中借用连接的超时(以秒为单位) spring.jta.atomikos.connectionfactory.ignore-session-transacted-flag = true #创建会话时是否忽略事务标志 spring.jta.atomikos.connectionfactory.local-transaction-mode = false #是否需要本地事务 spring.jta.atomikos.connectionfactory.maintenance-interval = 60 #池的维护线程运行之间的时间(以秒为单位) spring.jta.atomikos.connectionfactory.max-idle-time = 60 #从池中清除连接之后的时间(以秒为单位) spring.jta.atomikos.connectionfactory.max-lifetime = 0 #在被破坏之前可以将连接合并的时间(以秒为单位) 0表示无限制 spring.jta.atomikos.connectionfactory.max-pool-size = 1 #池的最大大小 spring.jta.atomikos.connectionfactory.min-pool-size = 1 #池的最小大小 spring.jta.atomikos.connectionfactory.reap-timeout = 0 #借用连接的收获超时(以秒为单位) 0表示无限制 spring.jta.atomikos.connectionfactory.unique-resource-name = jmsConnectionFactory #用于在恢复期间标识资源的唯一名称 spring.jta.atomikos.datasource.borrow-connection-timeout = 30 #从池中借出连接的超时(秒) spring.jta.atomikos.datasource.default-isolation-level = #池提供的连接的默认隔离级别 spring.jta.atomikos.datasource.login-timeout = #用于建立数据库连接的超时(以秒为单位) spring.jta.atomikos.datasource.maintenance-interval = 60 #池的维护线程运行之间的时间(以秒为单位) spring.jta.atomikos.datasource.max-idle-time = 60 #从池中清除连接之后的时间(以秒为单位) spring.jta.atomikos.datasource.max-lifetime = 0 #在被破坏之前可以将连接合并的时间(以秒为单位) 0表示无限制 spring.jta.atomikos.datasource.max-pool-size = 1 #池的最大大小 spring.jta.atomikos.datasource.min-pool-size = 1 #池的最小大小 spring.jta.atomikos.datasource.reap-timeout = 0 #借用连接的收获超时(以秒为单位) 0表示无限制 spring.jta.atomikos.datasource.test-query = #用于在返回连接之前验证连接的SQL查询或语句 spring.jta.atomikos.datasource.unique-resource-name = dataSource #用于在恢复期间识别资源的唯一名称 # BITRONIX spring.jta.bitronix.connectionfactory.acquire-increment = 1 #生成池时要创建的连接数 spring.jta.bitronix.connectionfactory.acquisition-interval = 1 #在获取无效连接后再次尝试获取连接之前等待的时间(以秒为单位) spring.jta.bitronix.connectionfactory.acquisition-timeout = 30 #从池中获取连接的超时(以秒为单位) spring.jta.bitronix.connectionfactory.allow-local-transactions = true #事务管理器是否允许混合XA和非XA事务 spring.jta.bitronix.connectionfactory.apply-transaction-timeout = false #当XAResource被登记时,是否应该设置事务超时 spring.jta.bitronix.connectionfactory.automatic-enlisting-enabled = true #资源是否应该被自动登记和删除 spring.jta.bitronix.connectionfactory.cache-producer-consumer = true #是否生产和消费者应该被缓存 spring.jta.bitronix.connectionfactory.defer-connection-release = true #提供程序是否可以在同一连接上运行许多事务,并支持事务交织 spring.jta.bitronix.connectionfactory.ignore-recovery-failures = false #是否应忽略恢复失败 spring.jta.bitronix.connectionfactory.max-idle-time = 60 #从池中清除连接之后的时间(以秒为单位) spring.jta.bitronix.connectionfactory.max-pool-size = 10 #池的最大大小 0表示无限制 spring.jta.bitronix.connectionfactory.min-pool-size = 0 #池的最小大小 spring.jta.bitronix.connectionfactory.password = #用于连接到JMS提供程序的密码 spring.jta.bitronix.connectionfactory.share-transaction-connections = false #ACCESSIBLE状态中的连接是否可以在事务的上下文中共享 spring.jta.bitronix.connectionfactory.test-connections = true #从池中获取连接是否应该进行测试 spring.jta.bitronix.connectionfactory.two-pc-ordering-position = 1 #在两阶段提交期间该资源应该采取的位置(始终为Integer.MIN_VALUE,始终为Integer.MAX_VALUE) spring.jta.bitronix.connectionfactory.unique-name = jmsConnectionFactory #用于在恢复期间标识资源的唯一名称 spring.jta.bitronix.connectionfactory.use-tm-join = true启动XAResource时是否应使用TMJOIN spring.jta.bitronix.connectionfactory.user = #用于连接到JMS提供者的用户 spring.jta.bitronix.datasource.acquire-increment = 1 #生成池时要创建的连接数 spring.jta.bitronix.datasource.acquisition-interval = 1 #在获取无效连接后再尝试获取连接之前等待的时间(以秒为单位) spring.jta.bitronix.datasource.acquisition-timeout = 30 #从池中获取连接的超时(以秒为单位) spring.jta.bitronix.datasource.allow-local-transactions = true #事务管理器是否允许混合XA和非XA事务 spring.jta.bitronix.datasource.apply-transaction-timeout = false #当XAResource被登记时,是否应该设置事务超时 spring.jta.bitronix.datasource.automatic-enlisting-enabled = true #资源是否应该被登记和自动删除 spring.jta.bitronix.datasource.cursor-holdability = #连接的默认游标保持性 spring.jta.bitronix.datasource.defer-connection-release = true #数据库是否可以在同一连接上运行许多事务,并支持事务交织 spring.jta.bitronix.datasource.enable-jdbc4-connection-test = #从池中获取连接时是否调用Connection.isValid() spring.jta.bitronix.datasource.ignore-recovery-failures = false #是否应忽略恢复失败 spring.jta.bitronix.datasource.isolation-level = #连接的默认隔离级别 spring.jta.bitronix.datasource.local-auto-commit = #本地事务的默认自动提交模式 spring.jta.bitronix.datasource.login-timeout = #用于建立数据库连接的超时(以秒为单位) spring.jta.bitronix.datasource.max-idle-time = 60 #从池中清除连接之后的时间(以秒为单位) spring.jta.bitronix.datasource.max-pool-size = 10 #池的最大大小 0表示无限制 spring.jta.bitronix.datasource.min-pool-size = 0 #池的最小大小 spring.jta.bitronix.datasource.prepared-statement-cache-size = 0 #准备好的语句高速缓存的目标大小 0禁用缓存 spring.jta.bitronix.datasource.share-transaction-connections = false #ACCESSIBLE状态下的连接是否可以在事务的上下文中共享 spring.jta.bitronix.datasource.test-query = #用于在返回连接之前验证连接的SQL查询或语句 spring.jta.bitronix.datasource.two-pc-ordering-position = 1 #在两阶段提交期间该资源应该采取的位置(始终为Integer.MIN_VALUE,始终为Integer.MAX_VALUE) spring.jta.bitronix.datasource.unique-name = dataSource #用于在恢复期间标识资源的唯一名称 spring.jta.bitronix.datasource.use-tm-join = true启动XAResource时是否应使用TMJOIN # EMBEDDED MONGODB (EmbeddedMongoProperties) spring.mongodb.embedded.features = SYNC_DELAY #启用功能的逗号分隔列表 spring.mongodb.embedded.version = 2.6.10 #Mongo使用版本 # ---------------------------------------- # 整合属性 # ---------------------------------------- #ACTIVEMQ(ActiveMQProperties) spring.activemq.broker-url = #ActiveMQ代理的URL 默认自动生成 例如`tcp:// localhost:61616` spring.activemq.in-memory = true #指定默认代理URL是否应在内存中 如果指定了一个显式代理,则被忽略 spring.activemq.password = #登录密码的代理 spring.activemq.pooled = false #指定是否创建PooledConnectionFactory而不是常规的ConnectionFactory spring.activemq.user = #代理登录用户 # ARTEMIS (ArtemisProperties) spring.artemis.embedded.cluster-password = #群集密码 默认情况下随机生成 spring.artemis.embedded.data-directory = #日志文件目录 如果持久性被关闭,则不需要 spring.artemis.embedded.enabled = true #如果Artemis服务器API可用,启用嵌入式模式 spring.artemis.embedded.persistent = false #启用持久存储 spring.artemis.embedded.queues = #启动时要创建的队列的逗号分隔列表 spring.artemis.embedded.server-id = #服务器ID 默认情况下,使用自动递增的计数器 spring.artemis.embedded.topics = #启动时要创建的主题的逗号分隔列表 spring.artemis.host = localhost #Artemis代理主机 spring.artemis.mode = #Artemis部署模式,默认情况下自动检测 可以显式设置为“native”或“embedded” spring.artemis.port = 61616 #Artemis 中间件端口 # SPRING BATCH(Batch 配置) spring.batch.initializer.enabled = true #如果需要,在启动时创建所需的批处理表 spring.batch.job.enabled = true #在启动时执行上下文中的所有Spring批处理作业 spring.batch.job.names = #在启动时执行的作业名称的逗号分隔列表(例如`job1,job2`) 默认情况下,执行在上下文中找到的所有作业 spring.batch.schema = classpath:org / springframework / batch / core / schema - @@ platform @@sql #用于初始化数据库模式的SQL文件的路径 spring.batch.table-prefix = #所有批次元数据表的表前缀 # HORNETQ (HornetQ 配置) spring.hornetq.embedded.cluster-password = #集群密码 默认情况下随机生成 spring.hornetq.embedded.data-directory = #日志文件目录 如果持久性被关闭,则不需要 spring.hornetq.embedded.enabled = true #如果HornetQ服务器API可用,启用嵌入式模式 spring.hornetq.embedded.persistent = false #启用持久存储 spring.hornetq.embedded.queues = #启动时要创建的队列的逗号分隔列表 spring.hornetq.embedded.server-id = #服务器ID 默认情况下,使用自动递增的计数器 spring.hornetq.embedded.topics = #在启动时创建的主题的逗号分隔列表 spring.hornetq.host = localhost #HornetQ代理主机 spring.hornetq.mode = #HornetQ部署模式,默认情况下自动检测 可以显式设置为“native”或“embedded” spring.hornetq.port = 5445 #HornetQ代理端口 # JMS (Jms 配置) # 连接工厂JNDI名称 设置时,优先于其他连接工厂自动配置 spring.jms.jndi-name= # 容器的确认模式 默认情况下,监听器被自动确认处理 spring.jms.listener.acknowledge-mode= # 启动时自动启动容器 spring.jms.listener.auto-startup= true # 最小并发消费者数 spring.jms.listener.concurrency= # 最大并发消费者数 spring.jms.listener.max-concurrency= # 指定默认的目的地类型是否为主题 spring.jms.pub-sub-domain= false # RABBIT (Rabbit 配置) # 客户端应连接到的逗号分隔的地址列表 spring.rabbitmq.addresses = spring.rabbitmq.dynamic = true # 创建一个AmqpAdmin bean spring.rabbitmq.host = localhost# RabbitMQ主机 spring.rabbitmq.listener.acknowledge-mode = # 容器的确认模式 spring.rabbitmq.listener.auto-startup = true# 启动时自动启动容器 spring.rabbitmq.listener.concurrency = # 最少消费者数 spring.rabbitmq.listener.max-concurrency = # 最大消费者数 spring.rabbitmq.listener.prefetch = # 在单个请求中要处理的消息数它应该大于或等于事务大小(如果使用) spring.rabbitmq.listener.transaction-size = # 在事务中要处理的消息数为了获得最佳结果,它应该小于或等于预取计数 spring.rabbitmq.password = # 登录以对代理进行身份验证 spring.rabbitmq.port = 5672# RabbitMQ端口 spring.rabbitmq.requested-heartbeat = # 请求的心跳超时,以秒为单位;零为无 spring.rabbitmq.ssl.enabled = false# 启用SSL支持 spring.rabbitmq.ssl.key-store = # 保存SSL证书的密钥存储区的路径 spring.rabbitmq.ssl.key-store-password = # 用于访问密钥库的密码 spring.rabbitmq.ssl.trust-store = # 保存SSL证书的Trust存储 spring.rabbitmq.ssl.trust-store-password = # 用于访问信任存储的密码 spring.rabbitmq.username = # 登录用户对代理进行身份验证 spring.rabbitmq.virtual-host = # 连接到代理时使用的虚拟主机 # 端点配置(EndpointCorsProperties) # 设置是否支持凭据 未设置时,不支持凭据 endpoints.cors.allow-credentials= # 在请求中允许的头文件逗号分隔列表 '*'允许所有标题 endpoints.cors.allowed-headers= # 逗号分隔的允许的方法列表 '*'允许所有方法 endpoints.cors.allowed-methods= GET # 逗号分隔的起始列表允许 '*'允许所有来源 未设置时,禁用CORS支持 endpoints.cors.allowed-origins= # 包含在响应中的标题的逗号分隔列表 endpoints.cors.exposed-headers= # 客户端可以缓存飞行前请求的响应时间(秒) endpoints.cors.max-age= 1800 # JMX ENDPOINT (EndpointMBeanExportProperties) (端点MBean导出属性) # JMX域名 如果设置为'spring.jmx.default-domain'的值初始化 endpoints.jmx.domain= # 启用所有端点的JMX导出 endpoints.jmx.enabled= true # 附加静态属性以附加到表示端点的MBean的所有对象名称 endpoints.jmx.static-names= # 确保在发生冲突时修改ObjectNames endpoints.jmx.unique-names= false # JOLOKIA JOLOKIA 配置 # 见Jolokia手册 jolokia.config.*= # 管理HTTP服务器(管理服务器属性) # 在每个响应中添加“X-Application-Context”HTTP头 management.add-application-context-header= true # 管理端点应绑定到的网络地址 management.address= # 管理端点上下文路径 例如`/ actuator` management.context-path= # 管理端点HTTP端口 默认使用与应用程序相同的端口 management.port= # 启用安全性 management.security.enabled= true # 访问管理端点所需的角色 management.security.role= ADMIN # 会话创建策略使用(always,never,if_required,stateless)(总是,永远,if_required,无状态) management.security.sessions= stateless # HEALTH INDICATORS (previously health.*) # 启用数据库运行状况检查 management.health.db.enabled= true # 启用默认的健康指标 management.health.defaults.enabled= true # 启用磁盘空间运行状况检查 management.health.diskspace.enabled= true # 用于计算可用磁盘空间的路径 management.health.diskspace.path= # 应该可用的最小磁盘空间(以字节为单位) management.health.diskspace.threshold= 0 # 启用弹性搜索健康检查 management.health.elasticsearch.enabled= true # 逗号分隔的索引名称 management.health.elasticsearch.indices= # 等待群集响应的时间(以毫秒为单位) management.health.elasticsearch.response-timeout= 100 # 启用JMS健康检查 management.health.jms.enabled= true # 启用邮件运行状况检查 management.health.mail.enabled= true # 启用MongoDB健康检查 management.health.mongo.enabled= true # 启用RabbitMQ运行状况检查 management.health.rabbit.enabled= true # 启用Redis健康检查 management.health.redis.enabled= true # 启用Solr运行状况检查 management.health.solr.enabled= true # 按照严重性的顺序,以逗号分隔的健康状态列表 management.health.status.order= DOWN, OUT_OF_SERVICE, UNKNOWN, UP # TRACING ((TraceProperties) 跟踪性能 # 跟踪中包含的项目 management.trace.include= request-headers,response-headers,errors # 远程 shell配置 # 验证类型 根据环境自动检测 shell.auth= simple # JAAS域 shell.auth.jaas.domain= my-domain # 验证密钥的路径 这应该指向一个有效的“.pem”文件 shell.auth.key.path= # 登录用户 shell.auth.simple.user.name= user # 登录用户的密码 shell.auth.simple.user.password= # 登录到CRaSH控制台的所需的角色,以逗号分隔列表 shell.auth.spring.roles= ADMIN # 用于查找命令的模式 shell.command-path-patterns= classpath*:/commands/**,classpath*:/crash/commands/** # 扫描更改并在必要时更新命令(以秒为单位) shell.command-refresh-interval= -1 # 用于查找配置的模式 shell.config-path-patterns= classpath*:/crash/* # 逗号分隔的要禁用的命令列表 shell.disabled-commands= jpa*,jdbc*,jndi* # 禁用逗号分隔的插件列表 默认情况下,根据环境禁用某些插件 shell.disabled-plugins= # 用户被提示再次登录后的毫秒数 shell.ssh.auth-timeout = # 启用CRaSH SSH支持 shell.ssh.enabled= true # 未使用的连接关闭之后的毫秒数 shell.ssh.idle-timeout = # SSH服务器密钥路径 shell.ssh.key-path= # SSH端口 shell.ssh.port= 2000 # 启用CRaSH telnet支持 如果TelnetPlugin可用,默认情况下启用 shell.telnet.enabled= false # Telnet端口 shell.telnet.port= 5000 # GIT 信息配置 # 生成的git信息属性文件的资源引用 spring.git.properties= # 标准出口 # 模式,告诉聚合器如何从源存储库中的键 spring.metrics.export.aggregate.key-pattern= # 全局存储库的前缀如果处于活动状态 spring.metrics.export.aggregate.prefix= # 导出刻度之间以毫秒为单位的延迟 按照这种延迟,指标将按计划导出到外部来源 spring.metrics.export.delay-millis= 5000 # 标志以启用度量标准导出(假设MetricWriter可用) spring.metrics.export.enabled= true # 要排除的度量名称列表 应用后包括 spring.metrics.export.excludes= # 要包含的度量名称的模式列表 spring.metrics.export.includes= # redis存储库导出的密钥(如果活动) spring.metrics.export.redis.key= keys.spring.metrics # redis存储库的前缀 如果处于活动状态 spring.metrics.export.redis.prefix= spring.metrics # 标志基于不导出不变的度量值来关闭任何可用的优化 spring.metrics.export.send-latest= # 主机的statsd服务器接收导出的指标 spring.metrics.export.statsd.host= # 接收导出指标的statsd服务器端口 spring.metrics.export.statsd.port= 8125 # statsd导出指标的前缀 spring.metrics.export.statsd.prefix= # 每个MetricWriter bean名称具有特定的触发器属性 spring.metrics.export.triggers.*= # ---------------------------------------- # DEVTOOLS属性 # ---------------------------------------- # DEVTOOLS(开发工具属性) # 启用一个livereload.com兼容的服务器 spring.devtools.livereload.enabled= true # # Server port. spring.devtools.livereload.port= 35729 # 应该排除的触发完全重新启动的其他模式 spring.devtools.restart.additional-exclude= # 观看更改的附加路径 spring.devtools.restart.additional-paths= # 启用自动重启功能 spring.devtools.restart.enabled= true # 应该排除的模式触发完全重新启动 spring.devtools.restart.exclude= META-INF/maven/**,META-INF/resources/**,resources/**,static/**,public/**,templates/**,**/*Test.class,**/*Tests.class,git.properties # 轮询类路径更改之间等待的时间量(以毫秒为单位) spring.devtools.restart.poll-interval= 1000 # 触发重新启动之前没有任何类路径更改所需的安静时间量(以毫秒为单位) spring.devtools.restart.quiet-period= 400 # 更改后的特定文件的名称将触发重新启动检查 如果未指定任何类路径文件更改将触发重新启动 spring.devtools.restart.trigger-file= # 远程开发工具属性 # 用于处理远程连接的上下文路径 spring.devtools.remote.context-path= /.~~spring-boot!~ # 启用远程调试支持 spring.devtools.remote.debug.enabled= true # 本地远程调试服务器端口 spring.devtools.remote.debug.local-port= 8000 # 用于连接到远程应用程序的代理主机 spring.devtools.remote.proxy.host= # 用于连接到远程应用程序的代理端口 spring.devtools.remote.proxy.port= # 启用远程重启 spring.devtools.remote.restart.enabled= true # 建立连接所需的共享密钥(需要启用远程支持) spring.devtools.remote.secret= # HTTP头用于传输共享密钥</ span> spring.devtools.remote.secret-header-name= X-AUTH-TOKEN
-
四、JSR303数据校验及多环境切换
-
常见参数:
@NotNull(message="名字不能为空") private String userName; @Max(value=120,message="年龄最大不能查过120") private int age; @Email(message="邮箱格式错误") private String email; 空检查 @Null 验证对象是否为null @NotNull 验证对象是否不为null, 无法查检长度为0的字符串 @NotBlank 检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格. @NotEmpty 检查约束元素是否为NULL或者是EMPTY. Booelan检查 @AssertTrue 验证 Boolean 对象是否为 true @AssertFalse 验证 Boolean 对象是否为 false 长度检查 @Size(min=, max=) 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内 @Length(min=, max=) string is between min and max included. 日期检查 @Past 验证 Date 和 Calendar 对象是否在当前时间之前 @Future 验证 Date 和 Calendar 对象是否在当前时间之后 @Pattern 验证 String 对象是否符合正则表达式的规则 .......等等 除此以外,我们还可以自定义一些数据校验规则
-
多环境切换
profile是Spring对不同环境提供不同配置功能的支持,可以通过激活不同的环境版本,实现快速切换环境;
-
多配置文件
我们在主配置文件编写的时候,文件名可以是 application-{profile}.properties/yml , 用来指定多个环境版本;
例如:
application-test.properties 代表测试环境配置
application-dev.properties 代表开发环境配置
但是Springboot并不会直接启动这些配置文件,它默认使用application.properties主配置文件;
我们需要通过一个配置来选择需要激活的环境:
# 比如在配置文件中指定使用dev环境,我们可以通过设置不同的端口号进行测试; # 我们启动SpringBoot,就可以看到已经切换到dev下的配置了; spring.profiles.active=dev
-
yaml的多文档块配置
server: port: 8081 #选择要激活那个环境块 spring: profiles: active: prod --- server: port: 8083 spring: profiles: dev #配置环境的名称 --- server: port: 8084 spring: profiles: prod #配置环境的名称
-
五、web开发
-
要解决的问题:
-
导入静态资源
目录建在:class path:/static(默认)下
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IMSGrbAZ-1622160885240)(springboot.assets/image-20210505104837848.png)]
可以存放静态资源的目录:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2kVL037y-1622160885243)(springboot.assets/image-20210505105322589.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vFqDb9Ai-1622160885244)(springboot.assets/image-20210505105544223.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ir6qaQWF-1622160885245)(springboot.assets/image-20210505105739098.png)]
-
首页
首页路径classpath:/static 或者 public目录下
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2nTkey8i-1622160885245)(springboot.assets/image-20210506195010659.png)]
显示结果:
源码分析:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6yq3lf9s-1622160885247)(springboot.assets/image-20210506200136131.png)]
注意
-
在templates文件夹下的目录不能直接映射过去,需要controller跳转过去
简言之,需要controller跳转的页面需要存放在tempaltes这个文件夹中,需要导入thymeleaf包
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4mvJMrv0-1622160885248)(springboot.assets/image-20210506201317416.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QU8sZJkE-1622160885248)(springboot.assets/image-20210506201330950.png)]
-
-
jsp\模板引擎thymeleaf
-
装配扩展SpringMvc
//配置webmvc @Configuration public class myConfig implements WebMvcConfigurer { @Override//看这部分 public void addViewControllers(ViewControllerRegistry registry) { //使用localhost:8080/ //使用localhost:8080/index.html都是跳转到index这个controller registry.addViewController("/").setViewName("index"); registry.addViewController("/index.html").setViewName("index"); } @Bean public LocaleResolver localeResolver(){ return new myLocalResolver(); } }
-
增删改查
-
拦截器
-
国际化
-
配置中英文配置文件
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-g6Q80XCM-1622160885249)(springboot.assets/image-20210510155659161.png)]
-
文件配置
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KowbEQOc-1622160885250)(springboot.assets/image-20210510155801489.png)]
-
前端页面书写方式:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GiRBoSem-1622160885251)(springboot.assets/image-20210510155918820.png)]
-
重写一个类
package com.warrior.boothello.config; import org.springframework.web.servlet.LocaleResolver; import org.thymeleaf.util.StringUtils; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Locale; //新建一个国际化类 public class myLocalResolver implements LocaleResolver { //解析请求 @Override public Locale resolveLocale(HttpServletRequest httpServletRequest) { String language = httpServletRequest.getParameter("l"); 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) { } }
-
注入到框架当中
package com.warrior.boothello.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; //配置webmvc @Configuration public class myConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("index"); registry.addViewController("/index.html").setViewName("index"); } @Bean//看这部分 public LocaleResolver localeResolver(){ return new myLocalResolver(); } }
-
-
-
框架模板
- bootstrap、layui、semantic-ui
- 后台模板:X-admin
六、swagger
- 世界上最流行的api框架;
- Restful Api文档在线自动生成工具->api文档与api定义同步更新
- 直接运行
-
在项目中使用swagger需要springfox
- swagger2
- ui
-
springboot集成swagger
-
maven
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
-
配置swagger
- config配置
package com.warrior.config; import org.springframework.context.annotation.Configuration; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration//配置类的注解 @EnableSwagger2//开启swagger2 public class SwaggerConfig { }
-
运行
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yDZw83Mr-1622160958875)(springboot.assets/image-20210519094638964.png)]
一些接口文档
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rKNLnZVe-1622160958876)(springboot.assets/image-20210519094732599.png)]
-
配置swagger
swagger的bean实例
@Configuration//配置类的注解 @EnableSwagger2//开启swagger2 public class SwaggerConfig { @Bean public Docket docket(){ return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()); } //作者信息 Contact contact = new Contact("warrior", "http://localhost:8080/", "zghblwz@163.com"); //配置swagger信息=apiInfo private ApiInfo apiInfo(){ return new ApiInfo("title", "description", "version", "http://localhost:8080", contact, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList()); } }
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GW84sG90-1622160958877)(springboot.assets/image-20210519100303464.png)]
配置后的页面
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5iFnVark-1622160958878)(springboot.assets/image-20210519100456195.png)]
-
swagger配置扫描接口
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wB671kBh-1622160958879)(springboot.assets/image-20210519101258793.png)]
-
关于通过不同的生产环境来判断是否开启swagger的测试
package com.warrior.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 springfox.documentation.builders.PathSelectors; 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//开启swagger2 public class SwaggerConfig { //管理前端页面的文档显示 @Bean public Docket docket(Environment environment){ //获取项目环境:Environment environment //设置要显示的swagger环境 Profiles profiles = Profiles.of("dev"); //通过environment.acceptsProfiles(profiles)判断自己是否处在设定的环境当中 boolean flag = environment.acceptsProfiles(profiles); return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) //enable:false关闭,true开启 .enable(flag) .select() //RequestHandlerSelectors,配置扫描接口的方式 //basePackage指定扫描的包 .apis(RequestHandlerSelectors.any()) //paths:过滤器扫描上边包里有下面的路径 // .paths(PathSelectors.ant("/student/**")) //扫描有这个接口的接口 .build(); } //作者信息 Contact contact = new Contact("warrior", "http://localhost:8080/", "zghblwz@163.com"); //配置swagger信息=apiInfo private ApiInfo apiInfo(){ return new ApiInfo("title", "description", "version", "http://localhost:8080", contact, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList()); } }
测试的过程:
然后就打不开文档页面
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TTlTTuSS-1622160958880)(springboot.assets/image-20210519110002644.png)]
-
切换测试环境
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tfFnIk2V-1622160958881)(springboot.assets/image-20210519110423510.png)]
-
-
-
配置api文档得分组
@Bean public Docket docket1(){//分组显示不同配置下得文件 return new Docket(DocumentationType.SWAGGER_2).groupName("warrior"); }
总结
提示:这里对文章进行总结:
例如:以上就是今天要讲的内容,本文仅仅简单介绍了pandas的使用,而pandas提供了大量能使我们快速便捷地处理数据的函数和方法。