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

  在使用Spring的过程当中,为了不大量使用Bean注入的Xml配置文件,咱们会采用Spring提供的自动扫描注入的方式,只须要添加几行自动注入的的配置,即可以完成html

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

Controller中当咱们调用某个Service时就不须要Set方法了,直接经过@Autowried 注解对Service对象进行注解便可:例如spring

在Controller中:api

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

在Service中oracle

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

Spring 中的XML配置:app

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

  一般,在Bean为添加@Component注解的状况下,在启动服务时,服务会提早报出如下代码中这样的异常状况下,此时应该检查相应Bean是否正确添加@Componentui

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

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

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注解:code

   在自动服务,spring初始化的时候,spring会把全部添加@Component注解的类做为使用自动扫描注入配置路径下的备选对象,同时在初始化spring@Autowired

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

   @Controller注解是一个特殊的Component,它容许了实现类能够经过扫描类配置路径的方式完成自动注入,一般@Controller是结合@RequestMapping注解一块儿使用的。

结语:

   经过了解Spring的注解能够帮助咱们在使用Spring开发过程当中提升开发效率,同时也增强了咱们对Spring的认识。在使用Spring开发的过程当中,我我的更倾向于使用注解的方式,减小配置文件代码。

相关文章
相关标签/搜索