注解总结

1. Spring注解

@component、@component(“userDao”):Dao、Service、Controller层类上;类上加此注解,把对象注入到IOC容器(在IOC容器加入的对象名称与类名相同,首字母小写);
@Resource、@Resource(name=“userService”):Dao、Service、Controller层类的属性字段;表示将IOC容器中已有的对象注入到此字段上;
@Autowired:Dao、Service、Controller层类的属性字段;将IOC容器中已有的对象自动注入到此字段上;

Spring注解@Autowired和@Resource区别对比

@Resource和@Autowired都是做bean的注入时使用;
@Autowired:是Spring提供的注解,需要导入包org.springframework.beans.factory.annotation.Autowired;只按照byType注入;
@Resource:由J2EE提供,需要导入包 javax.annotation.Resource;默认按照ByName自动注入;@Resource有两个重要的属性:name和type,而Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。所以,如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。如果既不制定name也不制定type属性,这时将通过反射机制使用byName自动注入策略;
详细参照:https://blog.csdn.net/renwendaojian/article/details/78586249
@Repository:Dao层类上;把对象注入到IOC容器;
@Service:Service层类上;把对象注入到IOC容器;
@Controller:Controller层类上;把对象注入到IOC容器;
@RequestMapping("/movie"):Controller类上、Controller方法上; 用于指定 url和请求方式,返回页面的 逻辑视图名(页面跳转时使用);
@PostMapping("/movie"):(Controller类上?)Controller方法上; 与@RequestMapping作用类似,用于指定 url,请求方式是 post请求;
@GetMapping("/movie"):(Controller类上?)Controller方法上; 与@RequestMapping作用类似,用于指定 url,请求方式是 get请求;
@PathVariable(“id”) Integer id:Controller类方法的参数上,Restful支持时使用;将方法上@RequestMapping指定的 url中 { }包起来的参数和后面跟的形参绑定(eg:);

@RequestMapping("/viewItems/{id}/{name}")
public @ResponseBody ItemsCustom viewItems(@PathVariable("id") Integer id) throws Exception{

}

@RequestParam(value=“item_id”,required=true,defaultValue=“1”)
Integer id:
Controller类方法的参数上,用于参数绑定;如果 request请求参数与 Controller方法中的形参名一致,适配器自动进行参数绑定;如果不一致,使用@RequestParam 注解 value属性 指明请求参数名;required属性 默认为 true,若没有参数则报错;defaultValue属性 设置默认值;
@ModelAttribute(value=“item”) ItemsCustom item:Controller类方法上、方法的参数上;用于方法的参数上,用于参数绑定,表示将请求的 POJO数据放到 model中; 用于方法上,将公用的取数据的方法返回值传到页面,不需要在每个 Controller方法中通过 Model传数据。;
@RequestBody :Controller类方法的参数;表示将请求的 JSON数据转成 JAVA对象,请求类型是 JSON格式数据;如果不是 JSON格式数据,则无需说明(eg:如下);
@ResponseBody:Controller类方法的返回类型;将 JAVA对象转成 JSON数据输出;在 Ajax时,用于Controller中相应的方法上,方法可返回 POJO对象和 List集合; 用在方法的返回类型参数前,表示返回即响应 JSON格式数据(eg:如下);

//请求 JSON,响应 JSON
@RequestMapping("/requestJson") 
public @ResponseBody ItemsCustom requestJson(@RequestBody ItemsCustom itemsCustom)throws Exception{ 
    return itemsCustom;
}
//请求 Key/Value,响应 JSON 
@RequestMapping("/responseJson") 
public @ResponseBody ItemsCustom responseJson(ItemsCustom itemsCustom)throws Exception{ 
    return itemsCustom; 
}

【自定义属性编辑器】
@InitBinder:Controller类中自定义属性编辑方法;表示添加自定义类型绑定(只可用于一个Controller中,多个 Controller中用时详见自定义参数绑定一节)eg:

//自定义属性编辑器 
@InitBinder 
public void initBinder(WebDataBinder binder)throws Exception{ 
	binder.registerCustomEditor(Date.class,new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
 }

【Validation校验器】
@Size(min=1,max=30,message="{items.name.length.error}",groups={ValidateGroup2.class}):实体类中的字段;message的值根据 properties文件中的 key来得到,当用到分组校验时加 groups属性;
@NotNull(message="{items.createtime.is.notnul}",groups={ValidateGroup1.class}):实体类中的字段;message的值根据 properties文件中的 key来得到; 在页面中显示错误信息,当用到分组校验时加 groups属性;
器中已有的对象自动注入到此字段上;
@Valid:Controller类中方法的参数;全部参数的最后面添加参数 (BindingResult bindingResult),传入BindingResult对象,用于获取校验失败情况下的反馈信息;
@Validated:Controller类中方法的参数;@Validated是@Valid 的一次封装,@Valid不提供分组功能,全部参数的最后面添加参数 (BindingResult bindingResult),传入BindingResult对象,用于获取校验失败情况下的反馈信息;eg:

@PostMapping("/girls")  //@Valid、BindingResult bindingResult
public Girl addGirl(@Valid Girl girl, BindingResult bindingResult) {
   if(bindingResult.hasErrors()){  
      System.out.println(bindingResult.getFieldError().getDefaultMessage());  
      return null;  
    } 
    return girlResposity.save(girl); 
} 
@RequestMapping("editSubmit") //@Valid、BindingResult bindingResult
public ModelAndView editSubmit(Model model,@Valid Movie movie,BindingResult bindingResult){
    movieRepository.save(movie);
    List<Movie> movieList=movieRepository.findAll();
    model.addAttribute("movieList",movieList);
    return new ModelAndView("/movie/list");
}

@RequestMapping("/editItemsSubmit") //@Validated 、BindingResult bindingResult
public String editItemsSubmit(Integer id,@Validated @ModelAttribute(value="itemsCustom") ItemsCustom itemsCustom,BindingResult bindingResult) throws Exception{ 

}

@Component
@Aspect:
切面类上;表示这是一个切面类。
@PointCut(“execution(* .())”):切面类中pointCut方法;pointCut方法是个空方法;
1. @Before(“execution(public void com.asd.spring.UserDao.save())”):切面类中方法上;此方法在业务代码之前执行;(没用到上面pointCut()方法时,直接写)
2. @Before(“pointCut()”):切面类中方法上;此方法在业务代码之前执行;
@After(“pointCut()”)切面类中方法上;此方法在业务代码之后执行,无论是否出现异常都执行;
@AfterReturning(“pointCut()”):切面类中方法上;此方法在业务代码后执行,若出现异常不执行;
@AfterThrowing(“pointCut()”):切面类中方法上;此方法在业务代码后,出现异常执行(即@AfterReturning与@AfterThrowing 两者不会同时存在);
@Around(“pointCut()”):切面类中方法上;此方法环绕业务代码,有参数joinPoint:joinPoint.proceed();方法proceed()相当于目标对象业务代码中的save();;


@Transactional:(Service层)类上、方法上;表示对应的 Service类或者 Service方法上存在事务(因为事务多在 Service层进行处理);

Spring注解@Autowired和@Resource区别对比

@Resource和@Autowired都是做bean的注入时使用;
@Autowired:是Spring提供的注解,需要导入包org.springframework.beans.factory.annotation.Autowired;只按照byType注入;
@Resource:由J2EE提供,需要导入包 javax.annotation.Resource;默认按照ByName自动注入;@Resource有两个重要的属性:name和type,而Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。所以,如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。如果既不制定name也不制定type属性,这时将通过反射机制使用byName自动注入策略;
详细参照:https://blog.csdn.net/renwendaojian/article/details/78586249

 

 

2. SpringBoot注解

@SpringBootApplication:运行主类上;告知系统这是一个 SpringBoot应用;
@ComponentScan(basePackages = “com.asd.springbootui”)运行主类上;可以表示扫描带有@Controller注解的类,;
@RestController:主类、Controller类上; 代表这是一个控制器类,直接 返回字符串内容 到页面上;
@Controller:Controller类上; 代表这是一个控制器类,返回页面的 逻辑视图名(页面跳转时使用);
@RequestMapping("/movie"):Controller类上、Controller方法上; 用于指定 url和请求方式,返回页面的 逻辑视图名(页面跳转时使用);


@Entity
@Table(name = “department”):
实体类上;都是(javax.persistence包中)@Entity表示这个类是一个实体,实体类与数据库表有映射关系;@Table表示实体类与数据库中相应的表有映射关系,设置数据库的表名;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY):
实体类中的字段上; @Id指明数据库的主键列, @GeneratedValue指明逐渐列值的生成方式(Mysql中自增);
@Column(name = “create_date”)
@DateTimeFormat(pattern = “yyyy-MM-dd HH:mm:ss”):
实体类中的日期字段上;@Column指明数据库中与实体类中对应不同名的字段;@DateTimeFormat设置日期类型的格式;
【对于一对一、一对多多对一:如果数据表中包含对应 id列,则直接使用@JoinColumn(name = “actor_id”,unique = true);如果不包含对应任何字段,则使用 mappedBy属性指明本身类名; 对于多对多:需要第三张关联关系表】
@OneToOne
@JoinColumn(name = “actor_id”,unique = true):
@OneToOne表示一对一关联关系; eg:Role类中private Actor actor;(数据表 role中有 actor_id)
@OneToOne(mappedBy = “actor”):@OneToOne表示一对一关联关系; eg:Actor类中private Role role;(数据表 actor中没有 关于 role的字段)
@OneToMany(cascade = CascadeType.ALL,targetEntity = Role.class, mappedBy = “movie”,fetch = FetchType.EAGER):@OneToMany表示多对一关联关系; eg:Movie类中private List<Role> roles=new ArrayList<Role>();(数据表 movie中没有 关于 role的字段)
@ManyToOne
@JoinColumn(name = “movie_id”):
实体类中包含的实体字段上;@ManyToOne表示多对一关联关系;@JoinColumn设置关联对象的外键列, eg:Role类中private Movie movie;;(数据表 role中包含 movie_id列)
@ManyToMany(cascade = {},fetch = FetchType.EAGER)
@JoinTable(name = “user_role”,joinColumns = {@JoinColumn(name = “user_id”)},inverseJoinColumns = {@JoinColumn(name = “roles_id”)}):
实体类中包含的集合字段上;@ManyToMany表示多对多:cascade用来设级联、fetch设置是否启用懒加载;@JoinTable保存多对多关联关系表的信息的设置:name表示第三张关联关系表的表名、joinColumns(加s是一个数组,所以用{}括起来)表示当前对象(User)在关联关系表(user_role)中的外键名(即user_id)、inverseJoinColumns (加s是一个数组,所以用{}括起来)表示关联的另一个多方(Role)在关联关系表(user_role)中的外键名(即roles_id);


@Configuration
@EnableJpaRepositories(basePackages = “com.asd.springbootdb.repositories”):
配置;@Configuration表示当前类是一个配置类,作用类似于Spring框架中的xml配置文件;@EnableJpaRepositories指定Repository类的包路径;
@Bean:(配置)类中的方法;告诉Spring框架这个方法的返回值需要注册成Spring中的 Bean;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = JpaConfiguration.class):
测试类上; @RunWith表示采用什么形式run:表示当前程序的运行是在spring的容器的环境下运行,而 junit可直接拿到 spring容器的对象,不需要再进行为重新得到 spring容器而进行的配置,简化了因为测试而生成相应的关于 spring容器的配置;@ContextConfiguration指明 jpa的配置文件,这里不是用xml文件进行配置,而是用 java的配置类进行配置的;
@Autowired:(测试)类中字段上;自动注入bean实体对象;
@Before:测试类中方法上;写具体的测试方法之前;
@Test:测试类中测试方法上;表示这是一个测试类;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值