SpringBoot 使用策略模式动态调用 Service
1. 项目目录

2. pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.6.3</version>
</dependency>
3. 创建测试类
TestController
package com.cnbai.controller;
import com.cnbai.service.ServiceContext;
import com.cnbai.service.TaskService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
public class TestController {
@Resource
private ServiceContext serviceContext;
@GetMapping("/test")
public void test(@RequestParam("type") String type) {
TaskService taskService = serviceContext.getTaskService(type);
taskService.task();
}
}
4. 创建 Service
TaskService
package com.cnbai.service;
import org.springframework.stereotype.Service;
/**
* 动态调用 service 父接口
*/
@Service
public interface TaskService {
void task();
}
ServiceContext
package com.cnbai.service;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Map;
/**
* 动态调用 service 处理类
*/
@Service
public class ServiceContext {
@Resource
private Map<String, TaskService> serviceMap;
public TaskService getTaskService(String type) {
return serviceMap.get(type);
}
}
UserService
package com.cnbai.service.impl;
import com.cnbai.service.TaskService;
import org.springframework.stereotype.Service;
@Service("user")
public class UserService implements TaskService {
@Override
public void task() {
System.out.println("user");
}
}
PersonService
package com.cnbai.service.impl;
import com.cnbai.service.TaskService;
import org.springframework.stereotype.Service;
@Service("person")
public class PersonService implements TaskService {
@Override
public void task() {
System.out.println("person");
}
}
5. 创建启动类
application
package com.cnbai;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class application {
public static void main(String[] args) {
SpringApplication.run(application.class, args);
}
}
6. 测试
http://localhost:8080/test?type=user
http://localhost:8080/test?type=person