GithubHelp home page GithubHelp logo

springboot笔记 about blog HOT 6 OPEN

zxy16305 avatar zxy16305 commented on August 30, 2024
springboot笔记

from blog.

Comments (6)

zxy16305 avatar zxy16305 commented on August 30, 2024 1

将spring boot作为一个非web应用使用

@SpringBootApplication
@Configuration
@PropertySource("file:comment.properties")
@EnableJpaRepositories("cn.showclear.repository")
public class ExcelApplication implements CommandLineRunner {
      public static void main(String[] args) {
            SpringApplication application = new SpringApplication(ExcelApplication.class);
            application.setWebEnvironment(false);
           SpringApplication.exit(application.run(args));
    }
    @Override
    public void run(String... args) throws Exception {
        //这里开始写主要的逻辑

    }
}

如果有根据传入参数来初始化的需求的话,根据传入参数生成临时配置文件,用 @PropertySource 导入;最后再删掉就好了(note: application.properties配置文件默认被IOS-8859的方式读取,使用.yml配置的话,就没有这个问题了 参考链接 )

优点是可以使用springboot配套的一系列框架,缺点就是启动springboot的时间还是比较长的,作为一个脚本,可能不是很能被接受

同时作为一个脚本,要关闭日志(特别是启动日志),加入配置logging.level.root=OFF关闭启动日志(root只是打个比方,这里写要关闭的日志类,最高是root。主要要关闭springframwork和数据库的日志

logging.level.org.springframework=OFF
logging.level.org.hibernate=off

)


spring boot 的灵活配置(参数)

spring boot获取参数的方式不要太多,在官方文档上,介绍了以下几种方式和他们之间的优先级:
(部分直接照搬原文是因为没有充分理解他的意思[没有写过])

  1. 开发工具的全局参数
  2. test中的@TestProtertySource 引入的参数
  3. springboot的test中 @SpringBootTest#properties 引入的参数
  4. 命令行参数(--name=xiaoMing)
  5. SPRING_APPLICATION_JSON中的参数
  6. ServletConfig的初始化参数
  7. ServletContext的初始化参数
  8. java:comp/env 中的JDNI属性
  9. java的系统变量(System.getProterties())
  10. 操作系统环境变量
  11. A RandomValuePropertySource that only has properties in random.*.
  12. Profile-specific application properties outside of your packaged jar (application-{profile}.properties and YAML variants)
  13. Profile-specific application properties packaged inside your jar (application-{profile}.properties and YAML variants)
  14. Application properties outside of your packaged jar (application.properties and YAML variants).
  15. Application properties packaged inside your jar (application.properties and YAML variants).
  16. @configuration 下的 @propertysource 注释.
  17. Default properties (specified using SpringApplication.setDefaultProperties).

包内配置文件的优先级:
1.当前目录的/config
2.当前目录
3.classpath/config
4.classpath


修改springboot默认启动图标

[在resource目录下新建banner.txt,内容为自己要输出的文字图标
文本绘字工具
也可以先用图片打印一遍,然后copy出来

from blog.

zxy16305 avatar zxy16305 commented on August 30, 2024

FAQ


spring boot 读取 .properties文件时中文乱码的问题

1.在 application.properties文件中加入以下配置

banner.charset=UTF-8
server.tomcat.uri-encoding=UTF-8
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
spring.messages.encoding=UTF-8

2.将IDE进行相关的设置(eg.intellij)
image

后记 :但是这样做后会导致.properties出现/xx/xx的的编码,需要用特定的编辑器才能可视化编辑。建议直接用.yml配置。

from blog.

zxy16305 avatar zxy16305 commented on August 30, 2024

spring boot 写测试类


在测试类上添加

@SpringBootTest()
@RunWith(SpringRunner.class)

就可以加载bean了
@ContextConfiguration(classes = Config.class)可以指定加载的config类

from blog.

zxy16305 avatar zxy16305 commented on August 30, 2024

springboot配置服务器符合CORS规范

简单来说,就是可以跨域调用数据接口

链接

按照这样配一下就好了 :滑稽:
前台本来是按照教程使用xmlHttpResquest,有点麻烦。
后来经过测试,jquery的ajax就可以使用(使用的版本是jquery-3.3.1)。

进一步验证(刚才是在本地的另一个端口的服务器前段进行的验证),在随便一个网页上(非https),插入jquery的js

(document.write("<script language='javascript' src='https://code.jquery.com/jquery-3.3.1.min.js'></script>");)

,再同样运行jquery的ajax请求本地服务器,得到了同样的结果

from blog.

zxy16305 avatar zxy16305 commented on August 30, 2024

文档阅读笔记①-基本配置篇

记录一些文档上提到的小tips


避免使用"default" package

更正上面的非Web应用的用法

虽然上面那种方法在应用上达到了要求,但在官方文档上的用法是不同的。
ApplicationRunner or CommandLineRunner 其中前者是传入封装好的命令行参数ApplicationArguments ,后者则是以String[]的形式传入。
用一个bean(@Componet)去实现接口,接口中的run方法会在SpringbootApplication.run(...)结束前调用,多个这样的bean可以用@Order控制调用顺序。
官方的原意应该是初始化命令行参数用的。

配置参数注入

environment variables,也就是系统的环境变量,部分操作系统不支持点(.)分割。此时用大写+下划线分割代替。
配置文件中可以使用${...}

配置文件分离

当配置过多时,为方便维护,可以将配置分离出去。
官方标准配置名为 application-{profile}.properties(或yml),当在spring.profiles.active配置里没有指定任何配置时,default被装载(即application-default.properties)。(也就是说配置了后default就失效了)
同时支持java代码配置 ,SpringApplication.setAdditionalProfiles(…​) 效果和上面一样

制定配置文件只要写{profile}部分即可,多个配置文件用逗号分离(也可以用yml的list写法: - value)。
(注意在spring.config.location配置了文件后,以上配置就失效了。如果要使用分离的配置文件,在spring.config.location里配置文件夹)

同时其配置文件也可以分离装载,在 @Component 上添加注解@Profile("profile"),可限制装载的配置文件。(配置必须是激活的)

参数注入

对象注入:@ConfigurationProperties("xxx")注释注入时,会自动将属性封装(多层)。

foo:
  list:
    - name: my name
      description: my description

上述会注入到注释为foo的bean中 的list对象中的两个属性。
同时多配置文件注入同一个参数,特指List,注入list并不会合并,而会覆盖,使用高优先权的List。

map的话也可以注入

foo:
  maps:
    key1:
      - value1
      - value2
    key2:
      - value3
      - value4

只要名字一样,甚至可以Enum


近似解析(demo里只成功了前两种)(知道原因了:@value不支持relaxed binding)

person.firstName
person.first-name
person.first_name 
PERSON_FIRST_NAME

关于spring boot的日志

默认使用的日志是Java Util Logging, Log4J2 and Logback.(其实无所谓)
日志默认是10m一篇循环。(ERROR/WARN/INFO)
另外专用的配置文件建议加上 "-spring",如"logback-spring.xml"(原因是因为这个配置文件可能在spring环境初始化完成之前就被log加载了,于是spring就不能完全的使用里面的配置 😂 )

from blog.

zxy16305 avatar zxy16305 commented on August 30, 2024

文档阅读笔记② -web篇

官网文档

具体可查看 WebMvcAutoConfiguration


默认情况下,spring boot 会加载以下内容(偷懒233)

  • Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.
  • Support for serving static resources, including support for WebJars (see below).
  • Automatic registration of Converter, GenericConverter, Formatter beans.
  • Support for HttpMessageConverters (see below).
  • Automatic registration of MessageCodesResolver (see below).
  • Static index.html support.
  • Custom Favicon support (see below).
  • Automatic use of a ConfigurableWebBindingInitializer bean (see below).

静态目录

  • 不要使用src/main/webapp,在打成jar包后不能正常工作(只能在war包下工作)。
    springboot 提供的默认静态目录是在classPath下的/static (或 /public 或/resources 或
    /META-INF/resources)
  • 同时资源目录是可以通过 spring.mvc.static-path-pattern=/xxx/**配置的,默认为/**。
    (注意这里只是匹配模式,也就可以理解为静态资源的过滤名字)
    也可以直接指定静态目录,spring.resources.static-locations,此时默认配置会被替换。

实践 update 2018 3 18

在实际使用中,发生了找不到静态资源的情况。此时这样指定(classpath):
`spring.resources.static-locations=classpath:/static/`
 或者干脆什么都不要动。springboot有些配置会破坏默认的配置,出现了问题要及时查阅文档
  • 另外还提到了特殊的 /webjars/** , wabjars是springboot推荐的前端的依赖管理。

  • 缓存破坏:需要配置以下内容(webjar)

spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**

随后会在静态资源链接后添加静态资源的content hash。


spring boot 应尽量避免JSP(嵌入式servlet容器的原因)

+ 打成jar包不能正常工作(tomcat文件匹配模式的硬编码/其他容器也差不多)
+ 有一些容器甚至不支持JSP(如Undertow)
+ 自定义的 error.jpp 不会覆盖默认的错误页面

自定义错误页面

在/error 目录下直接创建就好 如`404.html` , 甚至有 `5xx.ftl` 的写法(.ftl 是freemarker模板引擎文件)
但是没有·40x.ftl·的写法。

spring boot 的热部署

首先要引入spring-boot-devtools
springboot官方文档-spring-boot-devtools
然后参考 IntelliJ IDEA 使用spring-boot-devtools热部署无效解决办法进行配置

老问题了,idea不会自动编译resources下的东西。解决方式是把resources改成root,
或者在maven里配置编译的resources

建议 热部署啥的 还是自己手动编译一下好了,然后容器就会重装里面的内容的

from blog.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.