Spring Boot 插件化开发

  • 主程序负责最基础的功能
  • 为所有可插件化的功能设计接口
  • 开发插件jar包,完成后放到主程序的lib目录下
  • 主程序修改配置文件重启(或热加载)来加载功能
  • 每个接口有统一的测试方法,实现不同插件的测试

Serviceloader

serviceloader是java提供的spi模式的实现。按照接口开发实现类,而后配置,java通过ServiceLoader来实现统一接口不同实现的依次调用。与springboot结合后,该方式要实现的关键点有:

  • 在springboot启动时调用加载lib目录下所有jar包的方法。
  • 在需要调用服务时,使用ServiceLoader的方式来动态加载所有类。
  • 定义接口和实现类,接口必须在主程序中加载,实现类可以不在主程序中。
  • 实现示例
    这里没有在springboot启动时加载lib目录,而是为了测试方便在每次调用接口时都加载一次
    1
    2
    3
    4
    5
    //接口类
    package com.example.demo;
    public interface IHello {
    public void sayHello();
    }
1
2
3
4
5
6
7
//实现类,这个类可放在主程序中,也可以放在新的jar包里
public class dogHello implements IHello {
@Override
public void sayHello() {
System.out.println("WANG WANG");
}
}
1
2
3
4
5
6
7
8
9
//实现类,这个类可放在主程序中,也可以放在新的jar包里,这里放在catHello.jar中
package com.example.demo;

public class catHello implements IHello {
@Override
public void sayHello() {
System.out.println("MIAO MIAO");
}
}
1
2
3
// META-INF/services/com.example.demo.IHello 文件
com.example.demo.dogHello
com.example.demo.catHello
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//动态加载lib下所有jar包的方法
public class Utils {
public static String getApplicationFolder() {
String path = Utils.class.getProtectionDomain().getCodeSource().getLocation().getPath();
return new File(path).getParent();
}

public static void loadJarsFromAppFolder() throws Exception {
String path = "./lib";
File f = new File(path);
if (f.isDirectory()) {
for (File subf : f.listFiles()) {
if (subf.isFile()) {
loadJarFile(subf);
}
}
} else {
loadJarFile(f);
}
}

public static void loadJarFile(File path) throws Exception {
URL url = path.toURI().toURL();
// 可以获取到AppClassLoader,可以提到前面,不用每次都获取一次
URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
// 加载
Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
method.setAccessible(true);
method.invoke(classLoader, url);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//主程序
@SpringBootApplication
@Controller
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@RequestMapping(value = "/",method = RequestMethod.GET)
@ResponseBody
public String index() throws Exception {
Utils.loadJarsFromAppFolder();
ServiceLoader<IHello> serviceLoader= ServiceLoader.load(IHello.class);
for (IHello hello:serviceLoader){
hello.sayHello();
}
return "hello world!";
}
}

只需要把catHello.jar放在编译后代码的lib目录下,然后执行,就可以实现访问一次localhost:8080,就在控制台输出一次

1
2
WANG WANG
MIAO MIAO

此外,ServiceLoader这个类大部分是静态接口,其实我们可以自己复制一份改名称ProjectServiceLoader来进行修改,比如可以修改不从META-INF来加载等等,再说看看ServiceLoader源码还是很有趣的。

自定义方式

基于上面的方式,Serviceloader其实是有缺陷的,就是必须在META-INF里定义接口名称的文件,在文件中才能写上实现类的类名,如果一个项目里插件化的东西比较多,那很可能会出现越来越多配置文件的情况。
考虑把配置全部都放到application.yml里。

1
2
3
4
5
6
7
8
server :
port : 8080
impl:
//也可以考虑不在这里写包名,而是在程序里进行拼装
name : com.example.demo.IHello
clazz :
- com.example.demo.dogHello
- com.example.demo.catHello

接下来定义一下读取impl配置的类,这里用了lombok

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.example.demo.configuration;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties("impl")
@ToString
public class ClassImpl {
@Getter
@Setter
String name;

@Getter
@Setter
String[] clazz;
}

主程序里的代码改成:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.example.demo;

@SpringBootApplication
@Controller
@EnableConfigurationProperties({ClassImpl.class})
public class DemoApplication {

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

@Autowired
ClassImpl classImpl;

@RequestMapping(value = "/",method = RequestMethod.GET)
@ResponseBody
public String index() throws Exception {
Utils.loadJarsFromAppFolder("lib");
for (int i=0;i<classImpl.getClazz().length;i++) {
Class helloClass= Class.forName(classImpl.getClazz()[i]);
IHello hello = (IHello) helloClass.newInstance();
hello.sayHello();
}
return "hello world!";
}

}

当然还有很多异常处理没有做,实际使用中要记得补上。还有就是java的反射机制效率并不高,所以要考虑反射出实例一次后,尽量尝试复用,这就要求接口设计要好一点了。

其实根据这样的模式,其实都可以实现在数据库中配置实现类了。

上面的两种方法基本其实脱离了springboot,直接使用java插件化的模式考虑了,后续可以进一步看看如何将加载到的jar包变成bean来调用。

区分环境

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<!-- 环境信息 -->
<profiles>
<!-- 标机开发环境 -->
<profile>
<id>dev</id>
<properties>
<activeProfile>dev</activeProfile>
<serviceactive>servicedev</serviceactive>
<businessactive>businessdev</businessactive>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<!-- 测试环境 -->
<profile>
<id>test</id>
<properties>
<activeProfile>test</activeProfile>
<serviceactive>servicetest</serviceactive>
<businessactive>businesstest</businessactive>
</properties>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
</profile>
<!-- 生产环境 -->
<profile>
<id>product</id>
<properties>
<activeProfile>product</activeProfile>
<serviceactive>serviceproduct</serviceactive>
<businessactive>businessproduct</businessactive>
</properties>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
</profile>
</profiles>
1
2
3
4
# 指定执行环境
spring:
profiles:
active: @package.environment@
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<profiles>
<profile>
<id>dev</id>
<properties>
<package.environment>dev</package.environment>
</properties>
<!-- 是否默认 true表示默认-->
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>

<profile>
<id>test</id>
<properties>
<package.environment>test</package.environment>
</properties>
</profile>

<profile>
<!-- 生产环境 -->
<id>prod</id>
<properties>
<package.environment>prod</package.environment>
</properties>
</profile>
</profiles>

<build>
...
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>application.yml</include>
<include>application-${package.environment}.yml</include>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
...
</build>
1
2
# 指定环境打包
mvn clean package -P dev

参考插件

1
2
3
4
5
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.9.0.RELEASE</version>
</dependency>

参考资料

  1. Springboot插件化开发模式探索