精通Spring Boot——第五篇:寫一個spring-boot-starter包

爲了能更好的理解Springboot的自動配置和工做原理,咱們今天來手寫一個spring-boot-hello-starter。這個過程很簡單,代碼很少。接下來咱們看看怎麼開始實踐。 ##1. 新建maven工程。 這塊就不演示了,若是不會能夠自行百度...啦啦啦,由於太簡單了啊java

2.新建一個properties類

/**
 * @author Lee
 * @// TODO 2018/7/25-9:21
 * @description
 */
@ConfigurationProperties(prefix = "customer")
public class CustomerProperties {
    private static final String DEFAULT_NAME = "Lensen";

    private String name = DEFAULT_NAME;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

2.建立一個服務類CustomerServicegit

/**
 * @author Lee
 * @// TODO 2018/7/25-10:30
 * @description
 */
public class CustomerService {
    private String name;

    public String findCustomer(){
        return "The Customer is " + name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

3.AutoConfiguration類

/**
 * @author Lee
 * @// TODO 2018/7/25-10:32
 * @description
 */
@Configuration
@EnableConfigurationProperties(CustomerProperties.class)
@ConditionalOnClass(CustomerService.class)
@ConditionalOnProperty(prefix = "customer", value = "enabled", matchIfMissing = true)
public class CustomerAutoConfiguration {

    @Autowired
    private CustomerProperties customerProperties;

    @Bean
    @ConditionalOnMissingBean(CustomerService.class)
    public CustomerService customerService() {
        CustomerService customerService = new CustomerService();
        customerService.setName(customerProperties.getName());
        return customerService;
    }
}

##4. spring.factories配置github

在src/main/resources新建文件夾META-INF,而後新建一個spring.factories文件spring

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.developlee.configurer.CustomerAutoConfiguration

pom文件修改artifactId爲spring-boot-hello-starter 打包成jar. 而後用mvn install 安裝到本地mvn倉庫。 ##5. 測試spring-boot-hello-start 新建springboot工程,在pom.xml文件引入安裝的jar包springboot

<dependency>
		<groupId>com.developlee</groupId>
		<artifactId>spring-boot-hello-starter</artifactId>
		<version>1.0-SNAPSHOT</version>
	</dependency>

在項目啓動類中直接作測試:app

@SpringBootApplication
@RestController
public class TestStarterApplication {

	@Autowired
	CustomerService customerService;

	@GetMapping("/")
	public String index(){
		return customerService.getName();
	}

	public static void main(String[] args) {
		SpringApplication.run(TestStarterApplication.class, args);
	}
}

application.properties文件配置下咱們的customer.namemaven

customer.name = BigBBrother

接下來啓動項目,請求地址localhost:8080, 便可看到頁面上顯示BigBBrotherspring-boot

到這咱們已經完成了一個spring-boot-starter jar包的開發,有不少功能咱們能夠本身封裝成一個jar,之後要用直接引用就好了~ 這樣寫代碼是否是會有不同的體驗呢? 源代碼在個人github能夠找到哦測試

相關文章
相關標籤/搜索