携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第3天,点击查看活动详情
正文
如题:@Component可以替代@Controller吗
查看代码发现注解@Component、@Controller、@Service、@Repository都出自包org.springframework.stereotype。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Indexed
public @interface Component {
String value() default "";
}
Component注解的注释:表示带此注释的类是“组件”,在使用基于注释的配置和类路径扫描时,这些类被Spring自动检测注入容器中。@Controller、@Service、@Repository注解则是@Component的衍生注解。
也就是说,如果一个类上使用了@Component注解,那么就意味着同样也可以用@Controller、@Service、@Repository注解来替代它。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {
@AliasFor(annotation = Component.class)
String value() default "";
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {
@AliasFor(annotation = Component.class)
String value() default "";
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {
@AliasFor(annotation = Component.class)
String value() default "";
}
@Controller、@Service、@Repository就是针对不同的使用场景所采取的特定功能化的注解组件。
- @Controller用于标注控制层
- @Service 用于标注服务层,主要用来进行业务的逻辑处理
- @Repository用于标注数据访问组件
那么我们的问题是@Component可以替代@Controller、@Service、@Repository注解吗?为什么?
我一向尊崇实践出真理,动手。我将接口@Controller改成@Component后调用接口,接口请求成功。
网上说@Controller层是springMvc的注解,具有将请求进行转发、重定向的功能,我将代码改成如下后继续调用method方法,Url会因重定向变为method2。
@Component
@RequestMapping("/test")
public class TestController {
@RequestMapping("/method")
public String method(){
return "redirect:method2";
}
@RequestMapping("/method2")
public void method2(HttpServletResponse response) throws IOException {
response.setStatus(200);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().print("redirect请求接口成功");
}
使用@Component注解依然能够完成转发、重定向的功能。
我甚至将@Service注解都改为@Component,且让method2方法调用Service层,依然能够正常执行,AOP也能正常工作。
后续我又将POM中引入thymeleaf,接口返回String也能正常跳转html页面。
总结
除了@Controller有特定的意义之外,暂未发现使用@Component注解和@Controller有何不同。
以后遇到该问题,再来补充。