我在同一个 Maven 父模块下组合了 Web 和核心项目,如下所示,
家长 - 网络(com.parent.test.web) - 核心(com.parent.test.core)
我想引用核心项目中的Web模块依赖项来调用Web模块中的一些API
Web 项目示例,
com.test.parent.web
public interface RestInterface {
public ResponseEntity load();
}
@RestController
public class RestInterfaceImpl implements RestInterface {
@Override
@RequestMapping(value = "/getData", method = RequestMethod.GET, produces = APPLICATION_JSON)
public @ResponseBody ResponseEntity<Object> load() {
}
}
核心项目示例,
com.test.parent.core
@Component
public class CoreImpl implements CoreInterface {
// Is this possible to autowire
@Autowired
private RestInterface restInterface;
public boolean getOptions() {
ResponseEntity<Object> results = restInterface.load();
for (Object o : results) {
//TODO
}
}
}
因为项目是在同一个父pom模块中开发的。所有项目将被分组到一个 springboot jar 中,并将部署到同一个环境中。因此,我想将 Web 项目依赖项引用到核心项目中,并尝试扫描核心项目内的 Web 类。
我想澄清一些事情,
- 这是个好方法吗?
- 如果这是好方法,我们如何实现?
- 如果不是,那么正确的方法是什么?
最佳答案
恕我直言,这绝对不是正确的方法。关注点分离原则规定, Controller 应该只是从请求中获取参数的小段代码,将它们传递给业务类,然后转发到将显示结果的 View 。
如果您需要从核心类调用 Controller 的某些方法,则意味着您有一个胖丑陋的 Controller ,其中包含业务方法。正确的做法是将 Web 部分 => Controller 与业务部分 => 服务层分离。
这样,您就创建了一个服务 bean,它将在(现在很薄) Controller 和需要调用其方法的其他核心类中 Autowiring 。
关于java - Spring - 需要在 @Component 类中 Autowiring @RestController 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38788005/