springboot可以说是为了适用SOA服务出现,一方面,极大的简便了配置,加速了开发速度;第二方面,也是一个嵌入式的web服务,通过jar包运行就是一个web服务;

还有提供了很多metric,info等度量的初级接口,可以用于监控项目的情况。

以下,将会分三部分,总结springboot的整合:

1,springboot的搭建

2,springboot的默认配置原理

3,springmvc向springboot迁移,整合,基于(app后台框架搭建三)

==================================================================

1,springboot的搭建

我使用的idea是intellij,用intellij搭建springboot 很简单,如果使用eclipse也应该很简单,自己网上搜索教程就用了。但建议最好用intellij,确实功能强大很大。

创建第一个springboot项目:

选择spring initializr 然后选择下一步,spring cloudy项目是跟springboot紧密连在一起的,所以spring cloudy项目也可以这样搭建,只要引入相应的包就可以了。

设置包名,然后下一步:

选择依赖的包:

thymeleaf  模板引擎是springboot 推荐的,也是一个java视图模板,可是我个人不太喜欢,因为它是html严格模式的,例如input标签缺少一个 </input> 也会各种报错的。容错能力比较弱。

Lombok 是一个不错的组件,我们很多的bean类有大量的getting and setting 要我们去写,引入该包就可以不用写,在生成的类中,会自动为我们生成。

session 是spring组件,高度抽象的,可以跟redis整合,集中session管理,更加方便灵活。

还有一个spring组件 spring-reset-docs 是一个测试驱动的api文档生成组件,挺喜欢的一个组件,对我们测试成功的方法生成一个接口文档,当然出来的样式需要做一些微调。

这个spring-reset-docs网上没有什么资料,后面我整理一章

其他的依赖就是mybatis,aop等就不讲,你们可以根据具体的需求整合进去。

点击“finish” 完成项目的创建。

----------------------------------------------------------------------------------------------------------------------------

2,spring 默认配置原理

spring的启动类,需要配注解@SpringBootApplication 该注解是一个组合注解,他的核心功能是@EnableAutoConfiguration类

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import({ EnableAutoConfigurationImportSelector.class,
AutoConfigurationPackages.Registrar.class })
public @interface EnableAutoConfiguration { /**
* Exclude specific auto-configuration classes such that they will never be applied.
*/
Class<?>[] exclude() default {}; }

EnableAutoConfigurationImportSelector类使用了Spring Core包的SpringFactoriesLoader类的loadFactoryNamesof()方法。 
SpringFactoriesLoader会查询META-INF/spring.factories文件中包含的JAR文件(spring-boot-autoconfigure-1.3.x.jar )。 
当找到spring.factories文件后,SpringFactoriesLoader将查询配置文件命名的属性。在例子中,是org.springframework.boot.autoconfigure.EnableAutoConfiguration。 
在spring-boot-autoconfigure-1.3.x jar文件里,有一个spring.factories文件,该文件声明有哪些自动配置,内容如下:

# Initializers
org.springframework.context.ApplicationContextInitializer=\
org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer # Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.MessageSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
org.springframework.boot.autoconfigure.data.JpaRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.MongoRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.redis.RedisAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JmsTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\
org.springframework.boot.autoconfigure.mobile.DeviceResolverAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.MongoTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
org.springframework.boot.autoconfigure.reactor.ReactorAutoConfiguration,\
org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.FallbackWebSecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration,\
org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration,\
org.springframework.boot.autoconfigure.web.MultipartAutoConfiguration,\
org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration,\
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration

对于一些必须配置的项目,可以在appliaction.properties 或者application.yml 中配置,例如数据库连接的驱动,账户密码等

在Spring Boot的org.springframework.boot.autoconfigure.condition包中说明了使用@Conditional注释来加载配置,如果没有自定义配置就根据导入的jar包自动注入默认配置。

简单列举一些:

  • @ConditionalOnBean
  • @ConditionalOnClass
  • @ConditionalOnExpression
  • @ConditionalOnMissingBean
  • @ConditionalOnMissingClass
  • @ConditionalOnNotWebApplication
  • @ConditionalOnResource
  • @ConditionalOnWebApplication

以@ConditionalOnExpression注释为例,它允许在Spring的EL表达式中写一个条件。

@Conditional(OnExpressionCondition.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
public @interface ConditionalOnExpression { /**
* The SpEL expression to evaluate. Expression should return {@code true} if the
* condition passes or {@code false} if it fails.
*/
String value() default "true"; }

在这个类中,我们想利用@Conditional注释,条件在OnExpressionCondition类中定义:

public class OnExpressionCondition extends SpringBootCondition {

    @Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
// ...
// we first get a handle on the EL context via the ConditionContext boolean result = (Boolean) resolver.evaluate(expression, expressionContext); // ...
// here we create a message the user will see when debugging return new ConditionOutcome(result, message.toString());
}
}

在最后,@Conditional通过简单的布尔表达式(即ConditionOutcome方法)来决定。

官方文档:http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-troubleshoot-auto-configuration

---------------------------------------------------------------------------------------------------------------------------------

3,整合springboot ------app后台开发框架

3.1  配置application.properties

3.2  把 app后台框架搭建三的代码直接 拷贝过来放到指定的包下

这里,我就不多说了

3.3 springMVC的配置类也可以直接拉过来,不过做一下修改

/**
* Created by ouyangming on 2017/7/4.
* spring mvc configure
*/
@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter { private final static Logger logger = LoggerFactory.getLogger(WebMvcConfig.class); @Bean
public JwtUtil getJwtUtil(){
return new JwtUtil();
} //静态文件
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
logger.info("addResourceHandlers");
registry.addResourceHandler("/static/**").addResourceLocations("/WEB-INF/static/");
} @Bean
public FormatJsonReturnValueHandler JsonReturnHandler(){
FormatJsonReturnValueHandler formatJsonReturnValueHandler=new FormatJsonReturnValueHandler();
return formatJsonReturnValueHandler;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(getTokenHeader())
.addPathPatterns("/api/*")
.excludePathPatterns(
"/robots.txt");
} @Override
public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers) {
returnValueHandlers.add(JsonReturnHandler());
} //token 在header的拦截器
public HandlerInterceptor getTokenHeader(){
return new HeaderTokenInterceptor();
} }

-----------------------------------------------------------------------------------------------------------------------------------------------

4* 填坑说明

4.1  拦截器里无法直接注入类,必须要通过bean工厂进行注入

 if(jwtUtil==null){
BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(httpServletRequest.getServletContext());
jwtUtil = (JwtUtil) factory.getBean("jwtUtil");
}
token=jwtUtil.updateToken(token);
if(token.equals("0")){
dealErrorReturn(httpServletRequest,httpServletResponse,str);
}

4.2 自定义json的统一格式,无法直接返回字符串,因为默认的thymeleaf  的默认配置,会直接识别成默认视图名字,然后就去src/main/resources/templates找模板文件,找不到就直接报错。

例如下面就会直接报错了:

 @RequestMapping("/api/liu")
@AppResponsBody
public String loginSuccess(){
return "you are success login";
}

下一章,可能准备说一下springboot自动部署的jenkins的使用;

再后面会讲讲如何使用spring-reset-docs或者其他API的文档生成工具;

接下来就结合spring cloudy 或者dubbox 讲讲微服务的架构;

最后讲讲运维自动化集成, 高并发思路就差不多了。

源码下载链接:源码

QQ交流群:458419464

整合springboot(app后台框架搭建四)的更多相关文章

  1. springmvc跨域+token验证(app后台框架搭建二)

    这是app后台框架搭建的第二课,主要针对app应用是跨域的运用,讲解怎么配置跨域服务:其次讲解怎么进行token验证,通过拦截器设置token验证和把token设置到http报文中.主要有如下:   ...

  2. 自定义统一api返回json格式(app后台框架搭建三)

    在统一json自定义格式的方式有多种:1,直接重写@reposeBody的实现,2,自定义一个注解,自己去解析对象成为json字符串进行返回 第一种方式,我就不推荐,想弄得的话,可以自己去研究一下源码 ...

  3. spring4+srpingmvc+mybatis基本框架(app后台框架搭建一)

    前言: 随着spring 越来越强大,用spring4来搭建框架也是很快速,问题是你是对spring了解有多深入.如果你是新手,那么在搭建的过程中可以遇到各种各样奇葩的问题. SSM框架的搭建是作为我 ...

  4. spring4+springmvc+mybatis基本框架(app后台框架搭建一)

    前言: 随着spring 越来越强大,用spring4来搭建框架也是很快速,问题是你是对spring了解有多深入.如果你是新手,那么在搭建的过程中可以遇到各种各样奇葩的问题. SSM框架的搭建是作为我 ...

  5. .Net Core3.0 WebApi 项目框架搭建 四:JWT权限验证

    .Net Core3.0 WebApi 项目框架搭建:目录 什么是JWT 根据维基百科定义,JWT(读作 [/dʒɒt/]),即JSON Web Tokens,是一种基于JSON的.用于在网络上声明某 ...

  6. 从零开始--Spring项目整合(1)使用maven框架搭建项目

    这些年一直在用spring的框架搭建项目,现在开始我们从零开始利用Spring框架来搭建项目,目前我能想到有Spring.SpringMVC.SpringJDBC.Mybatis.WebSockt.R ...

  7. Unity 游戏框架搭建 (四) 简易有限状态机

    为什么用有限状态机?   之前做过一款跑酷游戏,跑酷角色有很多状态:跑.跳.二段跳.死亡等等.一开始是使用if/switch来切换状态,但是每次角色添加一个状态(提前没规划好),所有状态处理相关的代码 ...

  8. Windows下部署Appium教程(Android App自动化测试框架搭建)

    摘要: 1,appium是开源的移动端自动化测试框架: 2,appium可以测试原生的.混合的.以及移动端的web项目: 3,appium可以测试ios.android.firefox os: 4,a ...

  9. easyui 后台框架搭建

    近期公司要搭建一个后台管理项目.因为美工缺少 选择使用easyui jquery 框架 仅仅要懂点html js 这个用起来不是难事,看过API.在网上看了些 将它们组装起来 进行改动.因为本人也是第 ...

随机推荐

  1. Interface request structure used for socket ioctl's

    1. 结构体定义 /* * Interface request structure used for socket * ioctl's. All interface ioctl's must have ...

  2. BZOJ-4915-简单的数字题

    Description 对任意的四个不同的正整数组成的集合A={a_1,a_2,a_3,a_4 },记S_A=a_1+a_2+a_3+a_4,设n_A是满足a_i+a_j (1 ≤i<j≤4)| ...

  3. scala 读取文件遇到encode问题(Mac -> remote Linux)

    Source.fromFile(fileName)(enc: Encode),如果遇到错误: java.nio.charset.MalformedInputException: Input lengt ...

  4. swiper 初始化的两个小坑

    1.当swiper loop设为true时,同时你又改变了sliderPerview的值,这时候轮播,按prev按钮到第一个时,会出现空白页: 解决办法:sliderPerview设置为auto,lo ...

  5. php中get_headers函数的作用及用法的详细介绍

    get_headers() 是PHP系统级函数,他返回一个包含有服务器响应一个 HTTP 请求所发送的标头的数组.如果失败则返回 FALSE 并发出一条 E_WARNING 级别的错误信息(可用来判断 ...

  6. maven的介绍

    刚来通信行业的国企上班,面试的时候很尴尬的问道"maven是干什么的?"""maven是项目管理工具吗?是怎么管理的?(理解类似于协同等办公OA一样的软件了)& ...

  7. Unix/Linux僵尸进程

    1. 僵尸进程的产生: 一个进程调用exit命令结束自己生命的时候,其实它并没有真正的被销毁,而是留下一个称为“僵尸进程”的数据结构.这时它已经放弃了几乎所有内存空间,没有任何可执行代码,也不能被调度 ...

  8. LeetCode 79. Word Search(单词搜索)

    Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from l ...

  9. 【Win 10 应用开发】UI Composition 札记(一):视图框架的实现

    在开始今天的内容之前,老周先说一个问题,这个问题记得以前有人提过的. 设置 Windows.ApplicationModel.Core.CoreApplicationView.TitleBar.Ext ...

  10. 项目swift的一些问题

    在用swift做项目的时候,总会把之前oc的思想转过来. 1. 对Alamofire的再次封装,之前使用AFNetwork进行了在次封装,这样做的好处就是可以用一个全局的类来管理全部的网络请求,这样就 ...