zoukankan      html  css  js  c++  java
  • 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的耦合

  • 相关阅读:
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    网上怎么赚钱?如何利用CPA赚钱?
    在农村养殖什么赚钱?要做好哪些预防工作?
    计算机组成的基本硬件设备
    JAVA回溯法求0-1背包
    TensorFlow学习笔记之批归一化:tf.layers.batch_normalization()函数
    数据库连接池的大小值设定,不能随意设置太大的值
    N皇后问题
    19个强大、有趣、又好玩的 Linux 命令!
    JAVA马的遍历
  • 原文地址:https://www.cnblogs.com/xiaobaizhiqian/p/8120460.html
Copyright © 2011-2022 走看看