我认为Spring之所以流行,是因为spring starter模式,这可以让模块开发更加独立,相互依赖更加松散以及更加方便的继承。
话不多说,先写一个starter。
1. 创建一个maven工程,pom如下:
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.studyspring</groupId>
<artifactId>study-starter</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>study-starter</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.2.6.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>
2. 定义一个接口
package com.studyspring.studystarter;
public interface HelloService {
String sayHello();
}
3. 对接口做一个简单的实现,实际开发中肯定比这复杂
package com.studyspring.studystarter;
import org.springframework.stereotype.Component;
@Component
public class HelloServiceImpl implements HelloService {
@Override
public String sayHello() {
return "test starter...";
}
}
4. 创建一个配置类HelloServiceAutoConfiguration
package com.studyspring.studystarter;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.studyspring.studystarter")
public class HelloServiceAutoConfiguration {
}
这里,你会发现HelloServiceAutoConfiguration类中没有逻辑实现,它存在的目的仅仅是通过注解进行配置声明和扫描路径。到了这里,一个starter还剩最后一步,那就是声明这个配置类的路径,在Spring的根路径下建立META-INF\spring.factories文件,配置如下:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.studyspring.studystarter.HelloServiceAutoConfiguration
到此,一个标准的starter已经完成了。 使用方法,只需要打包mvn clean install,然后在其他的web项目引入该依赖:
<groupId>com.studyspring</groupId>
<artifactId>study-starter</artifactId>
<version>0.0.1-SNAPSHOT</version>
同时,添加Controller逻辑,如下:
import com.studyspring.studystarter.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@Autowired
private HelloService helloService;
@GetMapping("hellostart")
public String sayHello() {
return helloService.sayHello();
}
}
开发的starter对使用者来说非常的方便,除了在pom中引入依赖,什么都不需要做就可以直接在新项目中的接口中注入:
@Autowired
private HelloService helloService;
那么Spring Boot是怎么做到的呢?下一篇starter源码解析
参考书籍 《Spring源码深度分析》