Spring常用注解简述

@Component 

标注一个普通的spring Bean类

@Component可以代替@Repository、@Service、@Controller,因为这三个注解是被@Component标注的。但尽量使用对应组件注解的类替换@Component注解,在spring未来的版本中,@Controller,@Service,@Repository会携带更多语义。并且便于开发和维护。

@Controller

对应表现层的Bean

@ Service

对应的是业务层Bean

@ Repository

对应数据访问层Bean(即DAO组件)

@Repository(value="userDao")注解是告诉Spring,让Spring创建一个名字叫“userDao”的UserDaoImpl实例。


@Autowired 

自动装配,默认按类型装配

@Resource

作用相当于@Autowired,均可标注在字段或属性的setter方法上。

不同点:

  • @Autowired是Spring的注解,@Resource是javax.annotation注解

  • @Autowired默认按类型装配,@Resource默认按Name自动注入

  • @Resource注解的使用性更为灵活,可指定名称,也可以指定类型 ;@Autowired注解进行装配容易抛出异常,特别是装配的bean类型有多个的时候,而解决的办法是需要在增加@Qualifier进行限定。


@Scope

注解 作用域如@Scope("prototype")

spring MVC模块注解

web模块常用到的注解

@Controller 

表明该类会作为与前端作交互的控制层组件

@RequestMapping 

这个注解用于将url映射到整个处理类或者特定的处理请求的方法。可以只用通配符

@RequestParam 

将请求的参数绑定到方法中的参数上,有required参数,默认情况下,required=true,也就是改参数必须要传。如果改参数可以传可不传,可以配置required=false。

@RequestMapping("/happy")
  public String sayHappy(
  @RequestParam(value = "name", required = false) String name,
  @RequestParam(value = "age", required = true) String age) {
  //age参数必须传 ,name可传可不传
  ...
  }

@PathVariable 

该注解用于方法修饰方法参数,会将修饰的方法参数变为可供使用的uri变量

@RequestMapping(value="/happy/{dayid}",method=RequestMethod.GET)
public String findPet(@PathVariable String dayid, Model mode) {
//使用@PathVariable注解绑定 {dayid} 到String dayid
}

@RequestBody 

@RequestBody是指方法参数应该被绑定到HTTP请求Body上。

 

@ResponseBody 

@ResponseBody与@RequestBody类似,它的作用是将返回类型直接输入到HTTP response body中。

@ResponseBody在输出JSON格式的数据时,会经常用到。

@RequestMapping(value = "/happy", method =RequestMethod.POST)
@ResponseBody
public String helloWorld() {    
return "Hello World";//返回String类型
}

 

Spring事务模块注解

在处理dao层service层的事务操作时,譬如删除失败时的回滚操作。使用@Transactional作为注解,但是需要在配置文件**

<!-- 开启注解方式声明事务 -->

    <tx:annotation-driven transaction-manager="transactionManager" />

@Service
public class CompanyServiceImpl implements CompanyService {
  @Autowired
  private CompanyDAO companyDAO;
  @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class)
  public int deleteByName(String name) {
    int result = companyDAO.deleteByName(name);
    return result;
  }
  ...
}

其中的参数:

Spring常用注解简述

  • readOnly : 事务的读写属性,取true或者false,true为只读、默认为false

  • rollbackFor : 回滚策略,当遇到指定异常时回滚。譬如上例遇到异常就回滚

  • timeout (补充的) : 设置超时时间,单位为秒

  • isolation : 设置事务隔离级别,枚举类型,一共五种

Spring常用注解简述