springboot中使用工厂模式
- 工厂类
- 接口类
- 接口实现类
- controller类
工厂类
@Service
public class TestFactory {
@Autowired
private Map<String, TestInterface> map = new ConcurrentHashMap<String, TestInterface>();
public TestInterface geTestInterface(String key) {
System.out.println(key);
return map.get(key);
}
}
接口类
public interface TestInterface {
public String getMsg(String msg);
}
接口实现类
@Component("test1")
public class TestImpl1 implements TestInterface{
@Override
public String getMsg(String msg) {
return "test1:"+msg;
}
}
@Component("test2")
public class TestImpl2 implements TestInterface{
@Override
public String getMsg(String msg) {
return "test2:"+msg;
}
}
@Component("test3")
public class TestImpl3 implements TestInterface{
@Override
public String getMsg(String msg) {
return "test3:"+msg;
}
}
controller类
@RestController(value = "/")
public class TestController {
@Autowired
private TestFactory testFactory;
@RequestMapping(value = "msg/{key}",method = RequestMethod.GET)
public String getMsg(@PathVariable("key")String key) {
TestInterface test = testFactory.geTestInterface(key);
return test.getMsg("test test");
}
}