Spring Boot总结(3)---入口及配置详解
上篇通过快速搭建初步了解了SpringBoot,这篇详细讲述一些Spring Boot的项目启动核心。包括入口注解 @SpringBootApplication 和配置application.properties。
1.@SpringBootApplication
SpringBoot通常有一个名为 Application 的入口类,其main方法为入口方法,在main中使用SpringApplication.run来启动Spring Boot应用。SpringBootApplication是Spring Boot的核心注解,它是一个组合注解。
源码为:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
部分注解解释:
1.@EnableAutoConfiguration:让SpringBoot根据 类路径 中的jar包依赖为当前项目自动配置。如添加了spring-boot-starter-web依赖,会自动添加Tomcat和Spring MVC依赖,则Spring Boot会对Tomcat和Spring MVC进行自动配置。
2.application.properties
在src/main/resources目录下有一个全局配置文件:application.properties,可对一些默认配置的配置值进行修改。如我们常用的数据库配置,编码配置,服务器端口配置等。举例如下:
#for database
spring.datasource.url=jdbc:mysql://xx.xx.xx/xx?useUnicode=true&characterEncoding=UTF-8&useSSL=false
spring.datasource.username=xx
spring.datasource.password=xx
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#for server
server.port=8888
server.context-path=/helloDemo
server.tomcat.uri-encoding=UTF-8
spring.session.store-type=none
#for thymeleaf
spring.thymeleaf.cache=false
spring.thymeleaf.mode=LEGACYHTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
#for spring
spring.http.encoding.charset=UTF-8
spring.http.encoding.force=true
#for log
logging.file=/xx/log.log
logogging.level.org.springframework.web=debug
#for profile
#spring.profiles.active=dev/prod //用于配置两个application.properties
如果自己开发有更多需要配置的项的话,可参看官方常用配置列表,非常详细。
application.properties中除了一些配置项,还可以存储一些项目中必须全局使用的通用变量,如一些项目的token,用户账密等。可以直接在application.properties中添加:
如:
weber.name=weber
weber.sexy=boy
然后在项目需要使用的地方使用 @Value 注解注入,相当于初始化变量:
@Value("${weber.name}")
private String author;
Tips:
1.如果要多次使用配置值,也可使用@ConfigurationProperties来将一个properties属性和一个Bean及其属性关联,在需要使用的地方使用@autowired 注解来注入该配置声明Bean,通过get()、set()方法取值
2.如果要配置 两套配置(一般本地开发一套,线上一套),可使用profile配置。即配置两个application-xx1/2,properties,在application.properties中用spring.profiles.active=xx1/2 来选择使用哪个配置