javascript
Spring boot 系列 入门--配置
簡介
Spring Boot 并不是一個全新的框架,而是將已有的 Spring 組件整合起來。特點是去掉了繁瑣的 XML 配置,改使用約定或注解。所以熟悉了 Spring Boot 之后,開發效率將會提升一個檔次。
約定優于配置的這種做法在如今越來越流行了,它的特點是簡單、快速、便捷。但是這是建立在程序員熟悉這些約定的前提上。而 Spring 擁有一個龐大的生態體系,剛開始轉到 Spring Boot 完全舍棄 XML 時肯定是不習慣的,所以也會造成一些困擾。這里介紹一下一些常用的心得。
運行方式
spring-boot-starter-web包含了 Spring MVC 的相關依賴(包括 Json 支持的 Jackson 和數據校驗的 Hibernate Validator)和一個內置的 Tomcat 容器,這使得在開發階段可以直接通過main方法或是 JAR 包獨立運行一個 WEB 項目。而在部署階段也可以打成 WAR 包放到生產環境運行。
@SpringBootApplication public class Application extends SpringBootServletInitializer {@Overrideprotected SpringApplicationBuilder configure(SpringApplicationBuilder application) {return application.sources(Application.class);}public static void main(String[] args) throws Exception {SpringApplication.run(Application.class, args);}}在擁有@SpringBootApplication注解的類中,使用SpringApplication的run方法可以通過JAR啟動項目。
繼承SpringBootServletInitializer類并實現configure方法,使用application的sources方法可以通過WAR啟動項目。
note:
- @EnableAutoConfiguration 用于自動配置。簡單的說,它會根據你的pom配置(實際上應該是根據具體的依賴)來判斷這是一個什么應用,并創建相應的環境。
- @SpringBootApplication注解。很多Spring Boot開發者總是使用@Configuration,@EnableAutoConfiguration和@ComponentScan注解他們的main類。由于這些注解被如此頻繁地一塊使用(特別是你遵循以上最佳實踐時),Spring Boot提供一個方便的@SpringBootApplication選擇。該@SpringBootApplication注解等價于以默認屬性使用@Configuration,@EnableAutoConfiguration和@ComponentScan。
-
配置文件
Spring boot 的默認配置文件是resources下的application.properties和application.yml。
目前application.properties會出現中文亂碼問題,所有的properties文件都不是utf-8編碼,無法顯示中文,Spring Boot 總是會以iso-8859的編碼方式讀取該文件,后來改用 YAML 了就再也沒有出現過亂碼了。并且它也擁有更簡潔的語法,所以在此也更推薦使用application.yml作為默認的配置文件。
配置文件中可以定義一個叫做spring.profiles.active的屬性,該屬性可以根據運行環境自動讀取不同的配置文件。例如將該屬性定義為dev的話,Spring Boot 會額外從application-dev.yml文件中讀取該環境的配置。
Spring Boot 注入配置文件屬性的方法有兩種:
- 一種是通過@Value注解接受配置文件中的屬性
- 另外一種是通過@ConfigurationProperties注解通過set方法自動為Bean注入對應的屬性。
通過@Value注入屬性,接收者既可以是方法參數,也可以是成員變量。例如配置文件為:
dataSource:
url: jdbc:mysql://127.0.0.1:3306/test
username: test
password: test
filters: stat,slf4j
redis:
host: 192.168.1.222
port: 6379
通過@Value接受方法參數初始化Bean:
@Bean public JedisPool jedisPool(@Value("${redis.host}") String host,@Value("${redis.port}") int port) {return new JedisPool(host, port); }通過@ConfigurationProperties讀取配置初始化Bean,會直接調用對應的set方法注入:
@Bean(initMethod="init",destroyMethod="close") @ConfigurationProperties(prefix="dataSource") public DataSource dataSource() {return new DruidDataSource(); }Spring Boot 目前還無法直接注入的靜態變量。可以專門建立一個讀取配置文件的Bean,然后使用@PostConstruct注解修飾的方法對這些靜態屬性進行初始化,例如:
@Configuration public class ConstantsInitializer {@Value("${paging_size}")private String pagingSize;@PostConstructpublic void initConstants() {Constants.PAGING_SIZE = this.pagingSize;} }Servlet
Servlet 中最重要的配置文件就是web.xml,它的主要用途是配置Servlet映射和過濾器。而在 Spring Boot 中這將簡單很多,只需要將對應的Servlet和Filter定義為 Bean 即可。
聲明一個映射根路徑的 Servlet ,例如 Spring MVC 的DispatcherServlet:
@Bean public DispatcherServlet dispatcherServlet() {return new DispatcherServlet(); }需要注意的是,Spring Boot 默認會自動創建DispatcherServlet的映射。但這是在項目中沒有手動聲明其他 Servlet Bean 的情況下,否則就需要也將這個 Bean 一起聲明。
聲明一個映射特定路徑的 Servlet ,或是需要配置初始化參數的話,則需要使用ServletRegistrationBean。
例如 Druid 的StatViewServlet:
@Bean public ServletRegistrationBean statViewServlet() {ServletRegistrationBean reg = new ServletRegistrationBean();reg.setServlet(new StatViewServlet());reg.addUrlMappings("/druid/*");return reg; }聲明過濾器也是如此,例如 Spring MVC 的CharacterEncodingFilter:
@Bean public CharacterEncodingFilter characterEncodingFilter() {CharacterEncodingFilter filter = new CharacterEncodingFilter();filter.setEncoding("UTF-8");filter.setForceEncoding(true);return filter; }復雜一點的同樣是通過類似的FilterRegistrationBean,例如:
@Bean public FilterRegistrationBean appFilter() {FilterRegistrationBean reg = new FilterRegistrationBean();reg.setFilter(new LoggingFilter());reg.addUrlPatterns("/api/*");return reg; }Spring MVC
Spring MVC 主要的配置都可以通過繼承WebMvcConfigurerAdapter(或者WebMvcConfigurationSupport)類進行修改,這兩個類的主要方法有:
- addFormatters:增加格式化工具(用于接收參數)
- configureMessageConverters:配置消息轉換器(用于@RequestBody和@ResponseBody)
- configurePathMatch:配置路徑映射
- addArgumentResolvers:配置參數解析器(用于接收參數)
- addInterceptors:添加攔截器
總之幾乎所有關于 Spring MVC 都可以在這個類中配置。之后只需要將其設為@Configuration,Spring Boot 就會在運行時加載這些配置。
還有一些常用的 Bean 默認會自動創建,但是可以通過自定義進行覆蓋,例如負責 @RequestBody 和 @RequestBody 進行轉換的 MappingJackson2HttpMessageConverter 和 ObjectMapper,可以直接這樣覆蓋掉:
@Bean public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {return new CustomMappingJackson2HttpMessageConverter(); } @Bean public ObjectMapper jsonMapper(){ObjectMapper objectMapper = new ObjectMapper();//null輸出空字符串objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {@Overridepublic void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException {jgen.writeString("");}});return objectMapper; }DataSource
如果使用了spring-boot-starter-data-jpa,Spring Boot將會自動創建一個 DataSource Bean。可以直接在配置文件中定義它的屬性,前綴是spring.datasource。并且無需指定數據庫的方言,這個 Bean 會自動根據項目中依賴的數據庫驅動判斷使用的哪種數據庫。
同樣的,如果使用了spring-boot-starter-data-redis,也會自動創建RedisTemplate、ConnectionFactory等 Bean。也同樣可以在配置文件中定義屬性,前綴是spring.redis。
總結
以上是生活随笔為你收集整理的Spring boot 系列 入门--配置的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 手机是怎么计步的
- 下一篇: Spring boo系列--jpa和th