gpt4 book ai didi

java - Spring MVC 中的@Named 注解

转载 作者:太空狗 更新时间:2023-10-29 22:53:01 25 4
gpt4 key购买 nike

根据 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/18540696/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com