问题
I have combination of web and core projects under the same maven parent module as like,
Parent - Web (com.parent.test.web) - Core (com.parent.test.core)
I would like to refer the web module dependency in the core project to invoke some of the api from web module
Web project sample,
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() {
}
}
Core project sample,
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
}
}
}
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.
I'd like to get clarified on few things ,
- Is it the good approach ?
- If it is the good approach, how we can implement ?
- If not then what will be correct approach ?
回答1:
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.
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.
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.
来源:https://stackoverflow.com/questions/38788005/spring-need-to-autowire-restcontroller-class-in-a-component-class