原理#
依赖#
- Maven包含了SpringBoot的各种依赖
用户只需要引入启动器(spring-boot-starter-xxx),版本被依赖管理(父项目)
当然,不能这样引入的、偏僻的包也可以用老方法引入
自动配置 @SpringBootApplication#
@SpringBootApplication#
该注解将类注册为Bean并标注为SpringBoot应用(启动类)
其内main方法内的SpringApplication.run(启动类.class,args)将该应用启动#
- 推断程序是否为Web项目,设置监听器,设置main方法定义类(设置主类)
- 获取配置参数(核心配置文件、banner.txt等)
- 配置上下文、装配Bean等
@SpringBootConfiguration#
SpringBoot配置,是@Configuration修饰的@Component的组件
@EnableAutoConfiguration#
自动配置,将启动类下的所有包的东西导入
- @AutoConfigurationPackage
通过@Import({Registrar.class}),
将@SpringBootApplication注解的主程序类所在包及其子包下的“组件”扫描注册到Spring容器。 - @Import({AutoConfigurationImportSelector.class})
查找classpath中所有jar包的META-INF/spring.factories进行加载,选择性地将配置信息交给Spring容器进行创建。
总而言之#
@SpringBootApplication注解让Spring在启动时自动将maven导入了的starter(各种模块)加载,也把启动类目录之下的所有东西加载。
配置#
创建工程#
- 官网Spring Initilizer
- IDEA内置Spring Initilizer
- 需要勾选组件SpringWeb(内嵌Tomcat等)
通常还需要commons-io与commons-fileupload包
application.properties/yml#
SpringBoot的核心配置文件
常用配置#
- server.port=容器端口号
或ymlserver: port: 端口号
YAML语法 一定记得空格#
- 普通KV
key: value - 对象
object: key: false kkey: 2022/01/01object: {key: 1, kkey: 14514} - 数组
#行内 object: [阿黄, 阿龙] #多行 object: - value - vvalue
YAML能直接给实体类赋值(注入)#
类似于XML配置文件注入或@Value
- 在配置文件中按上述类的语法写好
- 要注入的类加上注解@ConfiguratrionProperties(prefix=“配置文件中的对象名”)
加载指定配置文件
@PropertySource(“classpath:xxx”)
@Value("${key}")
多配置#
- 多文件
- 可以在SpringBoot支持的目录下,保存各种名为application-xxx.yml文件
- 在默认的,最高优先级的配置文件中通过spring.profiles.active指定上面的xxx
- 单文件
- 在默认位置的配置文件中,用三个横杠
---分割各个配置不同的配置中,spring.profiles来命名 - 不同配置使用:命名区分
spring: config: activate: on-profile: xxx - 选择方式同多文件,卸载没有命名的、默认的配置中
- 在默认位置的配置文件中,用三个横杠
更换banner#
resources目录下的banner.txt
静态资源#
默认没有配置则按:classpath:resources > classpath:static > classpath:public 顺序
配置方法为spring.web.resources.static-locations: file:xxxx
静态资源映射为spring.mvc.static-path-pattern=URL格式,如/res/**则/res/img.jpg访问
放在templates目录下的,在模板引擎的支持下只能通过Controller的View进入,类似WEB-INF
SSL#
SpringBoot内置Tomcat只支持jks和pkcs12格式的密钥
转换方式
openssl pkcs12 -export -in xxx.pem/cer -inkey xxx.pem/key -out xxx.p12配置
server:
ssl:
key-store: 密钥文件路径
key-store-type: pkcs12/jks
key-store-password: 创建或转换时输入的口令首页与图标定制(类似welcome-page)#
- 首页index.html默认能放在上述的静态资源目录中
- 网站图标favicon.ico放在静态资源目录下(旧版本还需spring.mvc.favicon.enabled=false
使用#
数据校验 JSR303#
- 通常对POJO类使用,限制数据的内容。如限制为邮箱或符合某正则表达式的字符串。
- 如@NotNull, @Size, @Pattern等
认证#
SpringSecurity方式
需要导入依赖 spring-boot-starter-security
- 编写类继承WebSecurityConfigurerAdapter并@EnableWebSecurity
- 配置页面权限即配置了那些页面请求需要登录,并在没登录的时候跳转到一个登录界面。
protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("请求名称") .hasRole("需要的角色名"); http.formLogin();//启用框架自带登录页面 } - 配置角色
内存中用户角色:密码编码:protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("username") .password("114514") .roles("private_user");//.and().... }.passwordEncoder(new xxxPasswordEncoder())
