Spring注解@Controller
和@Service
一样吗?
我知道 @Controller
可用于 URL
映射和调用业务逻辑。
而@Service
用来注解包含业务逻辑的服务类。
我可以使用 @Controller
代替 @Service
来注解 Service 类吗?
最佳答案
不,它们彼此非常不同。
两者都是 @Component 注释的不同特化(实际上,它们是同一个接口(interface)的两个不同实现),因此两者都可以通过类路径扫描发现(如果您在 XML 中声明它)配置)
@Service 注释用于您的服务层并注释执行服务任务的类,通常您不使用它,但在许多情况下您使用此注释来表示最佳实践。例如,您可以直接调用 DAO 类来将对象持久保存到数据库中,但这很糟糕。调用一个调用 DAO 的服务类是很不错的。执行关注点分离模式是一件好事。
@Controller注解是Spring MVC框架中使用的注解(Spring Framework中用于实现Web应用的组件)。 @Controller 注解表明一个特定的类充当 Controller 的角色。 @Controller 注解充当注解类的构造型,指示其角色。调度程序扫描这些带注释的类以查找映射方法并检测@RequestMapping 注释。
因此,查看 Spring MVC 架构,您有一个 DispatcherServlet 类(您在 XML 配置中声明),它代表一个前端 Controller ,它将所有 HTTP 请求分派(dispatch)到适当的 Controller 类(由 @Controller 注释)。此类通过其方法执行业务逻辑(并可以调用服务)。这些类(或其方法)通常还使用 @RequestMapping 注释来指定 Controller 及其方法处理的 HTTP 请求。
例如:
@Controller
@RequestMapping("/appointments")
public class AppointmentsController {
private final AppointmentBook appointmentBook;
@Autowired
public AppointmentsController(AppointmentBook appointmentBook) {
this.appointmentBook = appointmentBook;
}
@RequestMapping(method = RequestMethod.GET)
public Map<String, Appointment> get() {
return appointmentBook.getAppointmentsForToday();
}
这个类是一个 Controller 。
这个类处理所有发往“/appointments”“文件夹”的HTTP请求,特别是get方法是处理所有发往文件夹“/appointments”的GET HTTP请求的方法。
我希望现在你更清楚了。
关于spring - Spring注解@Controller和@Service一样吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15922991/