Spring MVC中的@Named注释
Per Spring 3文档, IoC容器 , @Component
注释注释是与@Component
注释等效的标准。
由于@Repository
, @Service
@Controller
和@Controller
都是@Component
,我试图在我的Spring MVC应用程序中使用@Named
用于所有这些。 它工作正常。 但我发现@Controller
的替换似乎有一个bug。 在控制器类中,原来是
@Controller public class MyController{ ... }
它工作正常。 当我将@Controller
更改为@Named
@Named public class MyController{ ... }
它失败了,错误:
“找不到带有URI的HTTP请求的映射……”。
但是如果我将@RequestMapping
添加到类中,如下所示
@Named @RequestMapping public class MyController{ ... }
它会按预期工作。
对于@Repository
和@Service
,我可以简单地用@Named
替换它们,没有问题。 但是@Controller
的替换需要额外的工作。 我在配置中缺少什么?
@Named
工作方式与@Component
相同。 但是,注释@Controller
, @Service
@Controller
和@Repository
更具体。
来自Spring 文档 :
@Component
是任何Spring管理组件的通用@Component
型。@Repository
,@Service
@Controller
和@Controller
是@Component
用于更具体的用例,例如,分别在持久性,服务和表示层中。例如,这些刻板印象注释成为切入点的理想目标。 在未来的Spring Framework版本中,
@Repository
,@Service
@Controller
和@Controller
也可能带有额外的语义。 因此,如果您选择在服务层使用@Component
或@Service
Service,@Service
Service显然是更好的选择。 同样,如上所述,已经支持@Repository
作为持久层中自动exception转换的标记。
本节介绍与@Named
的区别。
许多组件,如Spring的DispatcherServlet
( WebApplicationContext
MVC配置)都没有查找Component
,他们正在寻找@Controller
。 所以当它扫描你的课时,它不会在@Named
找到它。 以类似的方式,使用@Transactional
事务管理查找@Service
和@Repository
,而不是更通用的@Component
。
所有@Repository
, @Service
@Controller
和@Controller
主要用于声明Spring bean,除了它为Spring提供有关bean类型的额外信息,如controller,dao等