外部配置
@Value
//application.properties
book.author=Owen
book.name=啦啦啦
//Book.kt
@Component
data class Book(@Value("\${book.author}") var author: String?,
@Value("\${book.name}") var name: String?)
//test
@RunWith(SpringRunner::class)
@SpringBootTest
class PropertiesTest{
@Autowired
var book: com.example.boot.domain.Book? = null
@Test
fun testBook(){
println(book)
//Book(author=Owen, name=啦啦啦)
}
}
@ConfigurationProperties
Spring booty也会使用这种方法来设定值
//只要改变Book.kt
@Component
@ConfigurationProperties(prefix = "book")
data class Book(var author: String?,
var name: String?)
日志配置
logging.level.org.springframework.web=INFO
logging.level.com.apress=DEBUG
logging.file=D:/mylog/web.log
Profile配置
会针对不同的环境,使用不一样的配置,如生产环境下会使用application-prod.properties文件
//application.properties, 使用prod配置文件
spring.profiles.active=prod
//application-prod.properties
server.port=80
//application-dev.properties
server.port=8080
运行原理
//核心是@EnableAutoConfiguration
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration{...}
@Conditional
- @ConditionalOnBean: 当容器有指定Bean的情况下
- @ConditionalOnClass: 当Classpath下有指定类的情况下
- @ConditionalOnExpression: 使用spel表达式作为判断条件
- @ConditionOnJava: 使用Java版本为判断条件
- @ConditionOnJndi: 在Jndi存在的条件下,查找指定的位置
- @ConditionOnMissingBean: 当容器没有指定Bean的情况下
- @ConditionalOnMissingClass: 当Classpath下没有指定类的情况下
-
- @ConditionalOnWebApplication: 当项目是web项目时
- @ConditionalOnNotWebApplication: 当项目不是web项目时
- @ConditionalOnProperty: 指定的属性是否有指定的值
- @ConditionalOnResource: 类路径是否有指定的值
- @ConditionalOnSingleCandidate: 当指定的Bean在容器中只有一个,或者有多个但是可以指定首选的
@org.springframework.context.annotation.Configuration
@ConditionalOnClass({ SqlSessionFactory.class, SqlSessionFactoryBean.class })
@ConditionalOnBean(DataSource.class)
@EnableConfigurationProperties(MybatisProperties.class)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class MybatisAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
factory.setDataSource(dataSource);
factory.setVfs(SpringBootVFS.class);
if (StringUtils.hasText(this.properties.getConfigLocation())) {
factory.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));
}
Configuration configuration = this.properties.getConfiguration();
if (configuration == null && !StringUtils.hasText(this.properties.getConfigLocation())) {
configuration = new Configuration();
}
if (configuration != null && !CollectionUtils.isEmpty(this.configurationCustomizers)) {
for (ConfigurationCustomizer customizer : this.configurationCustomizers) {
customizer.customize(configuration);
}
}
factory.setConfiguration(configuration);
if (this.properties.getConfigurationProperties() != null) {
factory.setConfigurationProperties(this.properties.getConfigurationProperties());
}
if (!ObjectUtils.isEmpty(this.interceptors)) {
factory.setPlugins(this.interceptors);
}
if (this.databaseIdProvider != null) {
factory.setDatabaseIdProvider(this.databaseIdProvider);
}
if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) {
factory.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
}
if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) {
factory.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());
}
if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) {
factory.setMapperLocations(this.properties.resolveMapperLocations());
}
return factory.getObject();
}
@Bean
@ConditionalOnMissingBean
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
ExecutorType executorType = this.properties.getExecutorType();
if (executorType != null) {
return new SqlSessionTemplate(sqlSessionFactory, executorType);
} else {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
Web开发
- 内嵌的Servlet容器:ServerPropertiesAutoConfiguration和ServerProperties自动配置
- HTTP报文的编码:HttpEncodingAutoConfiguration和HttpEncodingProperties
- 文件上传:MultipartAutoConfiguration和MultipartProperties
- mappingJackson2Http转换器:JacksonHttpMessage
- 配置Spring MVC:WebMvcAutoConfiguration和WebMvcProperties
配置WebMvcConfigurerAdapter
配置Thymeleaf
//默认配置
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.contentType=text/html
spring.thymeleaf.cache=true
Tomcat配置
也可代码基础TomcatEmbeddedServletContainerFactory。Jetty使用JettyEmbeddedServletContainerFactory
server.port= #默认端口为8080
server.session-timeout= #会话过期时间
server.context-path= #访问路径,默认/
server.tomcat.uri-encoding= #编码,默认UTF-8
server.tomcat.compression= #是否开启压缩,默认关闭
//使用jetty代替tomcat
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<!-- Exclude the Tomcat dependency -->
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Use Jetty instead -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
SSL
使用jdk/bin/keytool
keytool -genkey -alias tomcat
然后会生成一个.keystore文件,这个就是证书文件
server.ssl.key-store=.keystore
server.ssl.key-store-password=111111
server.ssl.keyStoreType=JKS
server.ssl.keyAlias=tomcat
server.ssl.key-password=another-secret
自动由http转向https
@Bean
public Connector connector(){
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocal");
connector.setScheme("http");
connector.setPort(8080);
connector.setSecure(false);
connector.setRedirectPort(8443);
return connector;
}
数据层
spring.jpa.hibernate.ddl-auto
create:
每次加载hibernate时都会删除上一次的生成的表,然后根据你的model类再重新来生成新表,哪怕两次没有任何改变也要这样执行,这就是导致数据库表数据丢失的一个重要原因。create-drop :
每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除。update:
最常用的属性,第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),以后加载hibernate时根据 model类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等 应用第一次运行起来后才会。validate :
每次加载hibernate时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但是会插入新值。
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/sakila
spring.datasource.username = root
spring.datasource.password = 123456
spring.jpa.hibernate.ddl-auto=update
#输出真实sql
spring.jpa.show-sql=true
#输出好看的json
spring.jackson.serialization.indent_out=true
#data-rest
spring.data.rest.base-path
spring.data.rest.default-page-size
spring.data.rest.limit-param-name
spring.data.rest.max-page-size
spring.data.rest.page-param-name
spring.data.rest.return-body-on-create
spring.data.rest.return-body-on-update
事务
直接可以用,使用@Transactional
缓存
开启:@EnableCaching
使用
- @Cacheable: 方法执行前,先查看缓存中是否有数据,有则直接返回,否则调用方法,返回值加入缓存
- @CachePut: 无论如何将返回值加入缓存
- @CacheEvict: 从缓存中删除
- @Caching: 组合多个注解策略
spring.cache.type #可选jcache,redis,guava,simple...
https://docs.spring.io/spring-boot/docs/2.0.0.BUILD-SNAPSHOT/reference/htmlsingle/#appendix