java - Spring MVC 中的@Named 注解

标签 java spring-mvc annotations jsr330

根据 Spring 3 文档,The IoC container , @Named 注释是标准的等同于 @Component 注释。

由于@Repository@Service@Controller都是@Component,我尝试使用@Named 用于我的 Spring MVC 应用程序中的所有这些。它工作正常。但是我发现 @Controller 的替换似乎有一个错误。在 Controller 类中,本来是

@Controller
public class MyController{
    ...
}

它工作正常。当我将 @Controller 更改为 @Named

@Named
public class MyController{
    ...
}

失败并出现错误:

"No mapping found for HTTP request with URI ...".

但是如果我将 @RequestMapping 添加到类中,如下所示

@Named
@RequestMapping
public class MyController{
     ...
 }

它会按预期工作。

对于@Repository@Service,我可以简单地将它们替换为@Named,没有问题。但是 @Controller 的替换需要额外的工作。配置中是否缺少任何内容?

最佳答案

@Named@Component 的工作原理相同。但是,注释 @Controller@Service@Repository 更加具体。

来自 Spring docs :

@Component is a generic stereotype for any Spring-managed component. @Repository, @Service, and @Controller are specializations of @Component for more specific use cases, for example, in the persistence, service, and presentation layers, respectively.

For example, these stereotype annotations make ideal targets for pointcuts. It is also possible that @Repository, @Service, and @Controller may carry additional semantics in future releases of the Spring Framework. Thus, if you are choosing between using @Component or @Service for your service layer, @Service is clearly the better choice. Similarly, as stated above, @Repository is already supported as a marker for automatic exception translation in your persistence layer.

This部分解释了与 @Named 的区别。

许多组件,如 Spring 的 DispatcherServlet(WebApplicationContext 中的 MVC 配置)并不是在寻找 Component,而是在寻找 @ Controller 。所以当它扫描你的类时,它不会在 @Named 中找到它。以类似的方式,使用 @Transactional 的事务管理查找 @Service@Repository,而不是更通用的 @Component.

关于java - Spring MVC 中的@Named 注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48141024/

相关文章:

java - 用于在 Android 上比较图像的 OpenGL ES 1.1/2.0 着色器

java - GUI 类(JTextField-JTextArea)

java - 我必须删除@Override 注释吗?

java - JAVA音频数据流0s

java - 基本递归枚举解释

tomcat - "Hello world"教程错误

Jquery UI 选项卡和 spring mvc

spring - 如何将 detectorHandlerMethodsInAncestorContexts 设置为 true?

java - 调用 Class.isAnnotationPresent(...) 有多昂贵?

java - 用于线程正确性的断言或注释