首页 技术 正文
技术 2022年11月7日
0 收藏 860 点赞 1,056 浏览 7693 个字

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(app后台框架搭建四)

创建第一个springboot项目:

整合springboot(app后台框架搭建四)

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

整合springboot(app后台框架搭建四)

设置包名,然后下一步:

整合springboot(app后台框架搭建四)

选择依赖的包:

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等就不讲,你们可以根据具体的需求整合进去。

整合springboot(app后台框架搭建四)

点击“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

整合springboot(app后台框架搭建四)

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

整合springboot(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

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,031
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,520
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,368
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,148
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,781
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,860