springboot使用的问题

xiaoxiao2025-07-29  28

1.Mapper.xml文件路径报错为Invalid bound statement (not found),mapper文件就放在新建的mapper文件夹里,路径配置为mapper/*.xml不会出错 2.springboot进行单元测试时文件头:

@RunWith(SpringRunner.class) @SpringBootTest @Component public class TestFather { @Before public void init(){ System.out.println(this.getClass().getName()+"开始测试了......"); } @After public void after(){ System.out.println(this.getClass().getName()+"测试结束了....."); } }

3.springboot热部署的问题 在使用IDEA做SpringBoot的web项目的时候,在每一次修改了java文件或者是resource的时候,都必须去重启一下项目,这样的话浪费了很多的时间(主要是心理感觉非常烦),那么,这个时候,就需要去实现程序的热部署,能够在修改了页面的时候能够立马刷新显现出新的效果。

第一步:添加热部署的maven依赖

<!--spring-boot-devtools 热启动依赖包--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> <scope>true</scope> </dependency>

第二步:添加maven插件(一般情况下假如用maven管理建立springboot程序的时候,就会自带这个插件的,所以你可以对比一下是否有或者一样,不一样进行修改)。

<plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin>

第三步:修改IDEA的设置File—>Other Settings—>Default Settings----->Compiler—>Bulid project automatically打上勾,就按照下图的勾去选择就行了(勾选完毕之后,一定记得点击Apply和Ok按钮使你的选择生效)。

第四步:打开IDEA,组合键Ctrl+Shift+Alt+/,弹出下面界面,选择Registry 或者是按住组合键Ctrl+Shift+A,弹出下面界面,输入Registry,选择第一个Registr 第五步:选择Registry,勾选complier.automake.allow.when.app.running 然后重启项目即可 参考: https://blog.csdn.net/qq_38455201/article/details/80078588 第四步:热部署相关配置,可解决热启动404问题

spring: devtools: restart: #poll-interval: 3s #检测classpath下是否有变化的周期,太短的话可能编译没完就restart,会404 #quiet-period: 2s trigger-file: trigger.txt #热部署配置,涉及方法签名或者接口变动时,需要修改trigger.txt热启动,方法内容变动不需要改动trigger,在resources下架trigger.txt文件

4.springboot的controller层进行junit测试

@Autowired WebApplicationContext webApplicationContext; //注入web环境 @Override @Before public void init() { super.init(); //拿到web上下文,其中就有spring管理的控制器了,这个参数需要整个web的上下文 mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build(); //MockMvcBuilders.standaloneSetup(new TestController()).build(); //这样指定一组控制器 } @org.junit.Test public void testController() throws Exception{ //mockMvc要在测试之前@before中设置好 mockMvc.perform(MockMvcRequestBuilders.get("/demoTest/test")//post和get请求 .param("param","this is junitTest")) //参数,可多个param方法,通过reqeust获取 .andDo(print()) //print()打印整个过程到控制台; .andExpect(MockMvcResultMatchers.content(). addExcect添加异常 string(Matchers.containsString("xiaoming"))) 这里是判断返回的结果中是否包含xiaoming,不包含的话抛异常出来,如下: } } 异常信息: java.lang.AssertionError: Response content Expected: a string containing "xiaoming" but: was "this is junitTest" Expected :a string containing "xiaoming" Actual :"this is junitTest" <Click to see difference>

5.springboot跟传统ssm项目比较的优势: (1)核心思想:约定优于配置 (2)优势:快速搭建项目,开发简单,配置简单; springboot是springcloud的基础 6.springboot的@validate对值进行校验,采用了Hibernate Validator 基本上包含了常用的数据校验,可以在校验值时省去烦人的空值或者大小的校验 参考:https://gitbook.cn/gitchat/column/5b86228ce15aa17d68b5b55a/topic/5baca87d80460e6b3d6f7abc

AccountBo中 @NotNull(message = "id不能为空") private String id; @Range(min = 0,max = 100,message = "balance最大值为100") private String accountNumber; @Range(min = 0,max = 100,message = "balance值需要在0-100之间") private Integer balance; @Pattern(regexp = "[^(fuck)]",message = "customName中有敏感词汇") private String customerName; 参数中使用时: //第二个BindingResult必须加,用于进行校验结果的获取 public List test(String param, @Valid AccountB accountB, BindingResult bindResult){ System.out.println("-----"+param); List<Map<Integer, AccountB>> list = new ArrayList<>(); if(bindResult.hasErrors()){ return bindResult.getAllErrors(); } return list; } 使用 mockMvc.perform(MockMvcRequestBuilders.get("/demoTest/test")//post和get请求 .param("param","this is junitTest") .param("accountB", JSONObject.toJSONString(accountB)) .param("accountNumber","300") ) //参数,可多个param方法,通过reqeust获取 .andDo(print()) //print()打印整个过程到控制台; // .andExpect(MockMvcResultMatchers.content(). // string(Matchers.containsString("this"))) .andReturn(); 结果: Body = [{"codes":["Range.accountB.accountNumber","Range.accountNumber","Range.java.lang.String","Range"],"arguments":[{"codes":["accountB.accountNumber","accountNumber"],"arguments":null,"defaultMessage":"accountNumber","code":"accountNumber"},100,0],"defaultMessage":"balance最大值为100","objectName":"accountB","field":"accountNumber","rejectedValue":"300","bindingFailure":false,"code":"Range"},{"codes":["NotNull.accountB.id","NotNull.id","NotNull.java.lang.String","NotNull"],"arguments":[{"codes":["accountB.id","id"],"arguments":null,"defaultMessage":"id","code":"id"}],"defaultMessage":"id不能为空","objectName":"accountB","field":"id","rejectedValue":null,"bindingFailure":false,"code":"NotNull"}]

7.springboot替换或者关闭启动时的文字图案,即banner (1)Spring Boot 默认寻找 Banner 的顺序是:

依次在 Classpath 下找 文件 banner.gif , banner.jpg , 和 banner.png , 先找到谁就用谁。 继续 Classpath 下找 banner.txt 上面都没有找到的话, 用默认的 SpringBootBanner 。

(2)替换步骤 第一步,制作文字图案 http://patorjk.com/software/taag/#p=display&f=Big&t=god%20bless 第二步:将文字复制到banner.txt下,放入resources中,然后编译即可 如果放多个banner的话,会将每个banner文件内容都打印出来 第三步:${spring-boot.version} 放在banner.txt中可打印boot版本 (3)控制banner开关,改造下主程序的main方法

SpringApplication app = new SpringApplication(MybatisDemoApplication.class); app.setBannerMode(Banner.Mode.OFF); app.run(args);

(4)一些佛祖保佑和神兽包保佑的banner https://blog.csdn.net/Kwoky/article/details/86346946 8.自定义配置文件,可以自定义属性,然后使用 (1)自定义配置属性的使用,在yml和properties中都可以

properties中配置 zsx.name=zhangshaoxuan 代码中使用$Value("${zsx.name}")取值 @Value("${zsx.name}") String name; public String getValue(){ return this.name; }

(2)可以通过实体类映射,将不同前缀的配置值,映射到实体类中

properties中 zsx.name=zhangshaoxuan zsx.gender=Male 实体类 @Component //标注为类,直接通过autowired使用 @ConfigurationProperties(prefix = "zsx") //配置前缀 public class ZsxProperties { String name; String gender; getter and setter方法... }

(3)springboot与maven结合进行多环境配置文件 i.都相同的配置放application.yml中,其他个性化配置 ii.在application.xml中配置

spring: profiles: active: @environment@

iii.在pom中配置profiles

<!--分别设置开发,测试,生产环境--> <profiles> <!-- 开发环境 --> <profile> <id>dev</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <environment>dev</environment> </properties> </profile> <!-- 测试环境 --> <profile> <id>sit</id> <activation> <activeByDefault>false</activeByDefault> </activation> <properties> <environment>sit</environment> </properties> </profile> ... </profiles>

iv.打包的时候选不同的profile即可 打完包后,application.yml中对应的就是选中的dev等 9.springboot中starter的作用和原理简介: (1)pom中的starter一个个starter可以看成是maven依赖组,每一组里面都提供了对应模块所需要的所有依赖,同是有一些starter其中还对默认配置做了设置,如对redis的请求端口默认设置为6379,实现了简化spring的复杂的xml配置和复杂的依赖管理的,达到开箱即用的效果

----springboot-starter-web这个starter中就提供了web,mvc,tomcat等依赖 <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.0.2.RELEASE</version> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-json</artifactId> <version>2.0.2.RELEASE</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <version>2.0.2.RELEASE</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0.9.Final</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.0.6.RELEASE</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.0.6.RELEASE</version> <scope>compile</scope> </dependency>

(2)springboot中做自动配置的原理 https://mp.weixin.qq.com/s/gs2zLSH6m9ijO0-pP2sr9Q i.@springbootApplication注解源码:

@SpringBootConfiguration ---这个继承的是spring的@Configuration,表示将启动类标记为一个bean @EnableAutoConfiguration --这个是自动配置的关键 @ComponentScan( --spring的扫描注解,将除了排除的类以外的其他注解bean全扫描到,交给spring容器 excludeFilters = {@Filter( type = FilterType.CUSTOM, classes = {TypeExcludeFilter.class} ), @Filter( type = FilterType.CUSTOM, classes = {AutoConfigurationExcludeFilter.class} )} )

ps:@ComponentScan扫描的默认路径是主启动类所在的包路径下,所以主启动类默认最好放在根路径,否则会有扫描不到bean的情况 ii.@EnableAutoConfiguration中的部分源码

@AutoConfigurationPackage @Import({AutoConfigurationImportSelector.class}) ---这个最重要 public @interface EnableAutoConfiguration { ... } AutoConfigurationImportSelector.java中用到了以下: SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());

iii.springFactoriesLoader会加载所有jar中的META-INF/spring.factories中的映射,最终会将所有配置了@ConfigurationProperties的pojo都加载到,并根据配置默认属性 eg: 类似于以下的pojo会被配置默认属性,如果application.xml配置文件中有配置属性,则会改变默认属性

@ConfigurationProperties( prefix = "spring.rabbitmq" ) public class RabbitProperties { private String host = "localhost"; private int port = 5672; private String username = "guest"; private String password = "guest"; .... }

(3)springApplication.run启动原理简介: 参考:https://zhuanlan.zhihu.com/p/99205565 i.启动流程图: ii. 启动过程: 总体分三步: 第一步:对springboot做一些初始化配置,包括main方法配置,是否web环境配置,创建监听器等操作 第二步:核心模块的启动,包括启动各种模块监听器,以及创建应用上下文环境 第三步:利用主启动类的注解进行自动化配置 springboot启动类: 1)进入run方法:

--静态run方法通过new一个初始化的springapplication实例调用实例run public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) { return (new SpringApplication(primarySources)).run(args); } --主要的作用是对springApplication这个对象做一些属性设置 public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) { this.sources = new LinkedHashSet(); this.bannerMode = Mode.CONSOLE; //设置banner .... this.primarySources = new ---配置资源路径LinkedHashSet(Arrays.asList(primarySources)); this.webApplicationType = this.deduceWebApplicationType(); this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class)); this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class)); --设置监听器 this.mainApplicationClass = this.deduceMainApplicationClass(); --设置主启动类 } --run方法继续: public ConfigurableApplicationContext run(String... args) { StopWatch stopWatch = new StopWatch(); stopWatch.start(); ConfigurableApplicationContext context = null; .... SpringApplicationRunListeners listeners = this.getRunListeners(args); --创建应用监听器开始监听 listeners.starting(); Collection exceptionReporters; try { ApplicationArguments applicationArguments = new DefaultApplicationArguments(args); ---这里配置环境信息,放到监听器中,读取配置资源并设置banner等 ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments); this.configureIgnoreBeanInfo(environment); Banner printedBanner = this.printBanner(environment); --创建应用上下文,见下面 context = this.createApplicationContext(); ----将上下文和环境。,监听器等做关联 this.prepareContext(context, environment, listeners, applicationArguments, printedBanner); ----这里主要调用的是refresh()方法,自动化配置的核心,调用springfactoriesLoader方法,同时实例化bean,是一个核心方法 this.refreshContext(context); this.afterRefresh(context, applicationArguments); stopWatch.stop(); if (this.logStartupInfo) { (new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch); } listeners.started(context); this.callRunners(context, applicationArguments); } catch (Throwable var10) { this.handleRunFailure(context, var10, exceptionReporters, listeners); throw new IllegalStateException(var10); } try { listeners.running(context); return context; } catch (Throwable var9) { this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null); throw new IllegalStateException(var9); } } ---创建应用上下文 protected ConfigurableApplicationContext createApplicationContext() { Class<?> contextClass = this.applicationContextClass; if (contextClass == null) { try {--这里对网络类型做判断 switch(this.webApplicationType) { case SERVLET: --servlet类型 contextClass = Class.forName("org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext"); break; case REACTIVE: contextClass = Class.forName("org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext"); break; default: --默认使用的AnnotationConfigApplicationContext对象,即通过扫描所有spring注解来创建bean contextClass = Class.forName("org.springframework.context.annotation.AnnotationConfigApplicationContext"); } .... } ---refresh 方法 在AbstractApplicationContext中 public void refresh() throws BeansException, IllegalStateException { synchronized(this.startupShutdownMonitor) { this.prepareRefresh(); ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory(); this.prepareBeanFactory(beanFactory); try { this.postProcessBeanFactory(beanFactory); this.invokeBeanFactoryPostProcessors(beanFactory); this.registerBeanPostProcessors(beanFactory); this.initMessageSource(); this.initApplicationEventMulticaster(); this.onRefresh(); this.registerListeners(); this.finishBeanFactoryInitialization(beanFactory); this.finishRefresh(); } catch (BeansException var9) { if (this.logger.isWarnEnabled()) { this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var9); } this.destroyBeans(); this.cancelRefresh(var9); throw var9; } finally { this.resetCommonCaches(); } } }

ps:以上总结起来就是:springboot启动主要做了判断配置环境比如是不是servlet的,创建整个应用的监听器,创建应用上下文,扫描注解,并根据上述环境生成bean放到spring容器中 2)进行springboot的自动配置 如上面springboot自动配置过程所述,主要是使用了springFactoriesLoader,即工厂加载器,读取了/META-INFO/spring.factories文件中配置的全类名通过反射获取这些类的构造器和默认的配置属性,再生成bean实例 10.springboot中配置文件上传大小和请求体大小

spring: servlet: multipart: max-file-size: 100MB max-request-size: 100MB

11.springboot中排除内置tomcat后打war 只需要继承一下初始化配置资源即可 如果想使用内置tomcat,则直接打jar包即可 12 springboot官网配置大全: https://docs.spring.io/spring-boot/docs/2.1.4.RELEASE/reference/htmlsingle/#using-boot-devtools 13.如果开发环境使用了springboot-devs-tool进行热部署,则会出现类加载器不一致的问题,默认情况下IDE中打开的代码都会使用dev的restart类加载器进行加载,而所有的jar包中的类都使用base类加载器(一般为appclassloader),这可能会出现一些问题,比如在引用类的静态属性时,发现后面取值与前面设置的值不一致的情况,官网的描述和解决方法: 原因:

By default, any open project in your IDE is loaded with the “restart” classloader, and any regular .jar file is loaded with the “base” classloader. If you work on a multi-module project, and not every module is imported into your IDE, you may need to customize things. To do so, you can create a META-INF/spring-devtools.properties file.

解决方法: The spring-devtools.properties file can contain properties prefixed with restart.exclude and restart.include. The include elements are items that should be pulled up into the “restart” classloader, and the exclude elements are items that should be pushed down into the “base” classloader. The value of the property is a regex pattern that is applied to the classpath, as shown in the following example:

restart.exclude.companycommonlibs=/mycorp-common-[\\w-]+\.jar restart.include.projectcommon=/mycorp-myproj-[\\w-]+\.jar

[Note] All property keys must be unique. As long as a property starts with restart.include. or restart.exclude. it is considered. [Tip] All META-INF/spring-devtools.properties from the classpath are loaded. You can package files inside your project, or in the libraries that the project consumes. 简单说,需要在跟路径下加上 META-INF/spring-devtools.properties,然后

restart.include开头的key是需要被restart类加载器加载的jar包路径 路径;restart.exclude开头的是不需要被restart类加载器加载的jar包路径 java -jar启动jar包时如果要开远程调试,则需要配置对应参数 eg: nohup java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=7777 -jar ./mccserver.ja

13.springboot中将vue打包后的项目集成进来的最简单方法: (1)在resources根路径下简历static文件夹,将打包后的项目内容直接复制到该文件夹 (2)创建一个handler返回index.html的名称 eg:

@RequestMapping(value={"/","/index"}) public ModelAndView index(){ ModelAndView mv = new ModelAndView("index.html"); return mv; }

(3)maven clean并重新打包,很重要 (4)如果出现图标不展示等情况,设置某些static文件不编码

<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <configuration> <nonFilteredFileExtensions> <nonFilteredFileExtension>ttf</nonFilteredFileExtension> <nonFilteredFileExtension>woff</nonFilteredFileExtension> <nonFilteredFileExtension>woff2</nonFilteredFileExtension> </nonFilteredFileExtensions> </configuration> </plugin>
转载请注明原文地址: https://www.6miu.com/read-5033948.html

最新回复(0)