码迷,mamicode.com
首页 > 编程语言 > 详细

SpringMVC---四大注解

时间:2017-12-26 23:12:34      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:false   get   通用   framework   ram   col   ati   ice   使用   

SpringMVC四大注解

  • Component

  通用标注,在不清楚使用哪个注解的时候,可以使用Component通用注解

  • Controller

  标注web请求控制器

  • Service

  标注Service层的服务

  • Repository

  标注DAO层的数据访问

四大注解都是类级别的,可以不带任何参数,也可以带一个参数,代表bean名字,在进行注入的时候就可以通过名字进行注入了。

bean的自动载入

在SpringMVC的配置文件中,通过context:component-scan使注解生效。这样就可以代替在web.xml中配置bean,自动实现bean的载入。例子:

<context:component-scan base-package="com.studySpringMVC.*">

  <context:include-filter type="annotation" expression="com.studySpringMVC.service"/>

  <context:exclude-filter type="annotation" expression=" com.studySpringMVC.service "/>

</context:component-scan>

context:include-filter定义需要扫描的包,context:exclude-filter定义不扫描的包,在配置时,两个标签的expression值不能设置成相同

type属性值有5个

Filter Type Examples Expression Description
annotation org.example.SomeAnnotation 符合SomeAnnoation的target class(被四大标注注释了的类)
assignable org.example.SomeClass 指定class或interface的全名
aspectj org.example..*Service AspectJ语法
regex org\.example\.Default.* Regelar Expression
custom org.example.MyTypeFilter Spring3新增自订Type,实作org.springframework.core.type.TypeFilter

 

 

 

 

 

使用@Resource或@Autowired注解实现注入

@Autowired默认按类型装配,默认情况下必须要求依赖对象必须存在,如果要允许null值,可以设置它的required属性为false(如@Autowired(required=false)),如果我们想使用名称装配可以结合@Qualifier注解进行使用

@Resource默认按名称进行装配,名称可以通过name属性进行指定,如果没有指定name属性,当注解写在字段上时,默认按字段名进行名称查找,如果注解写在setter方法上,默认取属性名进行装配。当找不到与名称匹配的bean时才按照类型进行装配。但是需要注意的是,如果name属性一旦指定,就只会按照名称进行装配。推荐使用@Resource,这个注解属于J2EE,减少了与Spring的耦合

SpringMVC---四大注解

标签:false   get   通用   framework   ram   col   ati   ice   使用   

原文地址:https://www.cnblogs.com/xiaobaizhiqian/p/8120460.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!