Spring常用注解

Spring注解分为两类,一种是使用bean(@Autowired , @Resource),另一种注册bean(如@Component , @Repository , @ Controller , @Service , @Configration)。

一、注册bean

@Repository、@Service、@Controller和 @Component 将类标识为Bean。
这4者都需要事先在xml中配置自动扫描功能
比如不使用注解的时候,我们需要在Spring-*.xml中配置每一个dao和每一个service

<bean id="userDao" class="com.springboot.demo.UserDao">
  <property name ="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="userService" class="com.springboot.demo.UserService">
  <property name ="userDao" ref= "userDao"></property>
</bean>

但是如果我们在Spring的xml中配置了,扫描注解的方式:

   <context:component-scan 
    base-package="com.gzsolartech.smartforms.dao,
			      com.gzsolartech.portal.service,
				  com.gzsolartech.smartforms.api" />
   <context:annotation-config />

就避免了每写一个service类或者dao类都得配置xml,我们只需要在写的service类上面写上@Service注解,在dao类上面写上@Repository注解就可以了

1.@Repository

@Repository主要是作用于DAO类上的,为了让spring能够扫描类路径的时候扫描并识别出@Repository,从而扫描到DAO。它的好处是就不用我们在xml中显示的配置扫描每一个Bean。方便了代码的书写,减少了程序员的配置复杂程度。

为什么 @Repository 只能标注在 DAO 类上呢?
这是因为该注解的作用不只是将类识别为Bean,同时它还能将所标注的类中抛出的数据访问异常封装为 Spring 的数据访问异常类型。 Spring本身提供了一个丰富的并且是与具体的数据访问技术无关的数据访问异常结构,用于封装不同的持久层框架抛出的异常,使得异常独立于底层的框架。

2.@Component

可以作用在任何层次,代表一个Bean。把普通pojo实例化到Spring容器中,相当于配置文件中的

<bean id="" class=""/>

3.@Service

通常作用在业务层,为了让Spring能够扫描类路径的时候识别业务层类。

4.@Controller

通常作用在控制层,可以让Spring在扫描的时候扫描到控制层的各个类。

5.@RequestMapping

RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。
RequestMapping注解有六个属性,下面我们把她分成三类进行说明。
5.1 value, method;
value:指定请求的实际地址,指定的地址可以是URI Template 模式(后面将会说明);
method:指定请求的method类型, GET、POST、PUT、DELETE等;

@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
public String findOwner(@PathVariable String ownerId, Model model) {
  Owner owner = ownerService.findOwner(ownerId);  
  model.addAttribute("owner", owner);  
  return "displayOwner"; 
}

5.2 consumes,produces;
consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;
produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;

@Controller
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public Pet getPet(@PathVariable String petId, Model model) {    
    // implementation omitted
}

5.3 params,headers;
params: 指定request中必须包含某些参数值是,才让该方法处理。
headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。

@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController {
@RequestMapping(value = "/pets", method = RequestMethod.GET, headers="Referer=http://www.ifeng.com/")
public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
// 仅处理request的header中包含了指定“Refer”请求头和对应值为
// “http://www.ifeng.com/”的请求;
  }
}

6.@responseBody注解

@responseBody注解的作用是将controller的方法返回的对象通过适当的转换器转换为指定的格式之后,写入到response对象的body区,通常用来返回JSON数据或者是XML数据

总结:
通过在不同层的类上面使用这些注解,Spring会自动创建不同层对应的BeanDefinition对象,并注册到ApplicationContext中,使Spring可以通过IOC来管理和使用这些Bean。

二、使用bean

@Resource和@Autowired注解,均可以对类成员变量、方法、以及构造函数进行标注,完成自动装配的工作。

1.@Autowired

(1)如果对成员变量使用了@Autowired注解,可以直接使用反射将标注的成员变量注入到Bean中,而省略getter和setter方法
(2)如果作用在构造函数上,会自动将构造函数所需的参数Bean注入

public class TestServiceImpl {
  // 下面两种@Autowired只要使用一种即可
  @Autowired
  private UserDao userDao; // 用于成员变量
  
  @Autowired
  public void setUserDao(UserDao userDao) { // 用于属性方法或者构造函数
    this.userDao = userDao;
  }
}

默认情况使用@Autowired是自动注入,所以需要在spring容器中必须有一个可供匹配的候选Bean,如果没有会抛出异常。要想避免这种异常,可以用@Autowired(required = false),告诉Spring,找不到Bean也无须报错。

使用@Autowired注解,代表的是按照Bean的类型装配(byType)。如果在spring容器中有两个以上的Bean符合装配条件,也会报错,此时我们就需要加上一个条件:"根据名称匹配"来避免出错。也就是使用 @Qualifier(“指定名称”)注解。

public class TestServiceImpl {
  @Autowired
  @Qualifier("userDao")
  private UserDao userDao; 
}

@Autowired 和@Qualifier 结合使用时,自动注入的策略就从 byType 转变成 byName 了。@Autowired 可以对成员变量、方法以及构造函数进行注释,而@Qualifier 的标注对象是成员变量、方法入参、构造函数入参。

2.@Resource

@Resource 默认按 byName 自动注入。@Resource有两个属性是比较重要的,分别是 name 和 type。

public class TestServiceImpl {
  // 下面两种@Resource只要使用一种即可
  @Resource(name="userDao")
  private UserDao userDao; // 用于字段上
  
  @Resource(name="userDao")
  public void setUserDao(UserDao userDao) { // 用于属性的setter方法上
    this.userDao = userDao;
  }
}

Spring 将@Resource 注释的 name 属性解析为 Bean 的名字,而 type 属性则解析为 Bean 的类型。所以如果使用 name 属性,则使用 byName 的自动注入策略,而使用 type 属性时则使用 byType 自动注入策略。如果既不指定 name 也不指定 type 属性,这时将通过反射机制使用 byName 自动注入策略
@Resource装配顺序:
①如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常。
②如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常。
③如果指定了type,则从上下文中找到类似匹配的唯一bean进行装配,找不到或是找到多个,都会抛出异常。
④如果既没有指定name,又没有指定type,则自动按照byName方式进行装配;如果没有匹配,则回退为一个原始类型进行匹配,如果匹配则自动装配。

@Resource和@Autowired的区别
@Autowired是属于Spring的注解,需要配置xml;包名org.springframework.beans.factory.annotation.Autowired
@Resource是属于J2EE的注解,需要引入jar包。包名javax.annotation.Resource

参考资料
https://www.jb51.net/article/169300.htm
https://blog.csdn.net/lishaoran369/article/details/74942407
https://www.cnblogs.com/shqnl/p/11337659.html
https://www.cnblogs.com/jpfss/p/9546142.html
https://blog.csdn.net/m0_37626813/article/details/78558010

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值