• SpringMVC---四大注解


    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的耦合

  • 相关阅读:
    jsop
    对象冒充call
    php中的static
    PHP对象在内存堆栈中的分配
    递归
    php简单日历
    php分页类
    请写一个函数,实现以下功能: 字符串“open_door” 转换成 “OpenDoor”、”make_by_id” 转换成 ”MakeById”
    php 计算两个文件之间的相对路径方法
    php冒泡排序
  • 原文地址:https://www.cnblogs.com/xiaobaizhiqian/p/8120460.html
Copyright © 2020-2023  润新知