Spring - 需要在 @Component 类中自动装配 @RestController 类 [英] Spring - Need to autowire @RestController class in a @Component class

查看:32
本文介绍了Spring - 需要在 @Component 类中自动装配 @RestController 类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在同一个 maven 父模块下组合了 web 和核心项目,

I have combination of web and core projects under the same maven parent module as like,

父母- 网络(com.parent.test.web)- 核心(com.parent.test.core)

Parent - Web (com.parent.test.web) - Core (com.parent.test.core)

我想引用核心项目中的web模块依赖来调用web模块中的一些api

I would like to refer the web module dependency in the core project to invoke some of the api from web module

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 类.

Because the projects are developed within the same parent pom module. All the projects will be grouped into a springboot jar and will be deployed into the same environment. So, I'd like to refer the web project dependency into the core project and trying to scan the web classes inside the core project.

我想澄清一些事情,

  • 这是好的方法吗?
  • 如果这是好的方法,我们如何实施?
  • 如果不是,那么正确的方法是什么?

推荐答案

恕我直言,这绝对不是正确的方法.关注点分离原则表示控制器应该只是一小段代码,它们从请求中获取参数,将它们传递给业务类,然后转发到将显示结果的视图.

IMHO it is definitely not a correct approach. The separation of concerns principle says that controllers should only be small pieces of code that take parameters from the requests, pass them to business classes, and forward to a view that will display the results.

如果你需要从一个核心类中调用控制器的一些方法,那就意味着你有一个胖丑的控制器,里面承载了业务方法.正确的做法是将Web部分=>控制器与业务部分=>服务层分开.

If you need to call some methods of the controller from a core class, it means but you have a Fat Ugly Controller carrying business methods inside it. The correct approach is to separate the web part => controller, from the business part => service layer.

这样您就可以创建一个服务 bean,它将在(现在是瘦的)控制器和需要调用其方法的其他核心类中自动装配.

That way you create a service bean that will be autowired in both the (now thin) controller and the other core classes that need to call its methods.

这篇关于Spring - 需要在 @Component 类中自动装配 @RestController 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆