SpringBoot中级教程之SpringBoot自定义配置(十一)
前言首先力推下我的开源项目
http://git.oschina.net/wangkang_daydayup/swagger-doc 这是一个完全利用spring boot开发的项目,拯救了springfox-swagger污染代码的问题,完全利用java-doc来实现,学习成本几乎是0
1.介绍
在Spring的代码中随处可见的@EnableAutoConfiguration
、@EnableWebMvc
、@EnableTransactionManagement
这些注解,通过使用这些注解来开启某项功能,下面的
例子就是来讲解如何定义自己的@EnableXXX
使用场景
官方介绍:If you work in a company that develops shared libraries, or if you work on an open-source or commercial library, you might want to develop your own auto-configuration. Auto-configuration classes can be bundled in external jars and still be picked-up by Spring Boot.
Auto-configuration can be associated to a “starter” that provides the auto-configuration code as well as the typical libraries that you would use with it. We will first cover what you need to know to build your own auto-configuration and we will move on to the typical steps required to create a custom starter.
大概意思是这样的:如果你在一个开发共享库的公司,或者是你想开发自己的auto-configuration,也就是说为spring boot开发一些自动配置的模块的时候,这个时候就需要用到这个技术,
完全可以通过一个注解或者引入一个jar包就开启这个功能
2.快速开始
下面是pom的配置 主要核心配置是spring-boot-configuration-processor
,这个是用来对注解进行处理的,官方解释是
You can easily generate your own configuration meta-data file from items annotated with @ConfigurationProperties
2.1 首先是pom.xml的配置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>springboot-11</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web