Spring 中@Component 注解,@Controller 注解详解

在使用 Spring 的过程中,为了避免大量使用 Bean 注入的 Xml 配置文件,我们会采用 Spring 提供的自动扫描注入的方式,只需要添加几行自动注入的的配置,便可以完成

Service 层,Controller 层等等的注入配置.使用过程中,在 Service 层中的实现类头上加@Compopnet 注解,在 Controller 类头加@Controller 注解,便完成了配置。例如在

Controller 中当我们调用某个 Service 时就不需要 Set 方法了,直接通过@Autowried 注解对 Service 对象进行注解即可:例如

在 Controller 中:

@Controller@RequestMapping("/test")
public class ExampleController {
     @Autowired  
     private ExampleService service;
}

在 Service 中

@Component
public class ExampleServiceImpl Implements ExampleService {
     @Autowired  
     private ExampleDao exampleDao;
}

Spring 中的 XML 配置:

<!-- 自动扫描service,controller组件 -->
<context:component-scan base-package="com.example.service.*"/>
<context:component-scan base-package="com.example.controller.*"/>

通常,在 Bean 为添加@Component 注解的情况下,在启动服务时,服务会提前报出以下代码中这样的异常情况下,此时应该检查相应 Bean 是否正确添加@Component

注解,而在 Controller 层中未配置@Controller 的情况,启动时服务可能不会爆出异常,但是你会发现页面请求中的 URL 地址是正确的,当时无论如何也访问不到 Controller 中相

对应的方法,这个时候就需要那么需要检查@Controller 注解和@RequestMapping 注解是否已经添加到 Class 上面了。

org.springframework.beans.factory.BeanCreationException:Error creating bean with name 'example'

No matching bean of type [com.example.ExampleService] found for dependency:
expected at least 1 bean which qualifies as autowire candidate for this dependency.
Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

下面就详细介绍下@Component,@Controller 注解:

org.springframework.stereotype.Component (implements java.lang.annotation.Annotation)   在自动服务,spring 初始化的时候,spring 会把所有添加@Component 注解的类作为使用自动扫描注入配置路径下的备选对象,同时在初始化 spring@Autowired

注解相应的 Bean 时,@Autowired 标签会自动寻找相应的备选对象完成对 bean 的注入工作。

org.springframework.stereotype.Controller (implements java.lang.annotation.Annotation)   @Controller 注解是一个特殊的 Component,它允许了实现类可以通过扫描类配置路径的方式完成自动注入,通常@Controller 是结合@RequestMapping 注解一起使用的。

结语:

   通过了解 Spring 的注解可以帮助我们在使用 Spring 开发过程中提高开发效率,同时也加强了我们对 Spring 的认识。在使用 Spring 开发的过程中,我个人更倾向于使用注解的方式,减少配置文件代码。


最后修改于 2013-12-24