能@Component,@Repository并@Service注释互换在Spring中,还是他们提供任何特殊的功能,除了作为一个符号设备?
换句话说,如果我有一个Service类并且我将注释更改@Service为@Component,它仍然会以相同的方式运行吗?
或者注释是否也会影响类的行为和功能?
我正在学习春天3,我似乎没有把握背后的功能<context:annotation-config>和<context:component-scan>.
根据我的阅读,他们似乎处理不同的注释(@ Required,@ Autowired etc vs @Component,@ Repository,@ Service等),但也从我读过的内容中注册了相同的bean后处理器类.
为了让我更加困惑,有一个@Required属性@Autowired.
有人可以对这些标签有所了解吗?什么是相似的,什么是不同的,一个被另一个取代,它们相互完成,我需要其中一个,两者都有吗?
前几天我开始研究这个Spring Hello World教程:http://viralpatel.net/blogs/spring-3-mvc-create-hello-world-application-spring-3-mvc/
在本教程中,使用spring-servlet.xml文件配置Spring DispatcherServlet ,这个文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="net.viralpatel.spring3.controller" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
Run Code Online (Sandbox Code Playgroud)
在这个文件中,我使用的上下文:组件扫描标签说,春天有扫描我的文件搜索的注释,因此,例如,当控制器类发现的方法是通过注解@RequestMapping("/你好")注释知道此方法处理以"/ hello"结尾的URL的HTTP请求.这很简单......
现在我的疑问与我可以在STS\Eclipse中自动构建的Spring MVC模板项目有关.
当我在STS中创建一个新的Spring MVC项目时,我的DispatcherServlet由一个名为servlet-context.xml的文件配置,该文件包含一些与前一个示例文件类似的配置.
在这个文件中,我仍然有组件扫描标记:
<context:component-scan base-package="com.mycompany.maventestwebapp" />
Run Code Online (Sandbox Code Playgroud)
但我还有另一个标签(看起来有类似的任务),这一个:
<annotation-driven />
Run Code Online (Sandbox Code Playgroud)
这两个标签有什么区别?
另一个"奇怪"的事情是,前一个示例(不使用注释驱动标记)与STS使用Spring MVC模板项目创建的项目非常相似,但是如果我从其配置中删除注释驱动标记文件项目不运行并给我以下错误:HTTP状态404 -
在堆栈跟踪中,我有:
WARN:org.springframework.web.servlet.PageNotFound - 未发现HTTP请求与URI [/ maventestwebapp /]在DispatcherServlet的映射名为 'appServlet'
但为什么?前面的示例在没有注释驱动标记的情况下运行良好,并且此控制器类非常相似.实际上,只有一种方法可以处理对"/"路径的HTTP请求
这是我的控制器类的代码:
package …Run Code Online (Sandbox Code Playgroud)