Spring&Mybatis系列容易忘记的注解

一.SpringBoot不常用注解

1. @ImportResource(locations = "classpath:applicationContext.xml")

locations = 指定targer目录下配置文件的位置注解是用在启动类上面,表示在SpringBoot启动的时候加载指定的配置文件

@Resource  //自动注入

2. @EnableConfigurationProperties({StudentProperties.class, AddressProperites.class})用在SpringBoot启动类上面,注解里面的参数是class类型的数组,作用是:启动的时候让指定的类放进Spring容器中,或者在每个类上面加入@Component注解

3.    @PropertySource(value = "classpath:db.properties")  //参数是指定targer目录下配置文件的位置一般用于pojo实体类上面,当项目启动的时候加载指定的配置文件,默认加载application.yml文件和@ConfigurationProperties(prefix = "jdbc.mysql"),连用表示加载classpath:db.properties文件并且把jdbc.mysql开头的属性赋值给实体类上面的成员变量

4. @Data //用在pojo实体类上表示开启get、set、tostring方法等

5. @NoArgsConstructor //用在pojo实体类上表示开启无参构造 @AllArgsConstructor //用在pojo实体类上表示开启有参构造

6. @Accessors(chain = true)  //用在pojo实体类上面开启对象中方法的链式调用

7.  @Slf4j   //用在controller类上面注解式日志

8. @DateTimeFormat(pattern = "yyyy-MM-dd")   //用在成员变量上接收参数时候日期格式化

9. @Repository //用在dao层@Repository和@Controller、@Service、@Component (用于其他) 的作用差不多,都是把对象交给spring管理。@Repository用在持久层的接口上,这个注解是将接口的一个实现类交给spring管理。

10. @Mapper   //用在dao层接口上将当前标注接口生成Mapper代理对象,并将代理对象放入IOC容器中

11. @MapperScan(basePackages = {"com.bjpowernode.dao", "com.bjpowernode.dao2"})

 用在启动类上面扫描指定包下所有的mappr接口放入IOC容器中

12.@Validated //作用在类、方法和参数上,是一套帮助我们继续对传输的参数进行数据校验的注解,通过配置Validation可以很轻松的完成对数据的约束。

 @Pattern(regexp = "^[1-9][0-9]{6,9}@[a-zA-Z0-9]{1,4}.[a-zA-Z0-9]{1,4}$",message = "邮箱格式不正确") //正则表达式

如果一个类中包含了另外一个实体类,那么在上面加上@Validated即可,比如上面的:

 public class XoPO {    
    @validated
    private List<PersonDetailPO> personList;
 }
@NotNull 数据不能为null
@NotEmpty 数据不能为null,不能为空字符串
@NotBlank 数据不能为null,不能为空字符串,不能由空白字符组成
@Size 校验数据、集合、字符串的长度
@Range 数组范围校验
@Email 邮箱校验
@Pattern(regexp="", message = "") 正则校验
通用配置项:message 校验失败时的提示信息

13. Aop

@Aspect:作用是把当前类标识为一个切面供容器读取
@Pointcut:Pointcut是植入Advice的触发条件。每个Pointcut的定义包括2部分,一是表达式,二是方法签名。方法签名必须是 public及void型。可以将Pointcut中的方法看作是一个被Advice引用的助记符,因为表达式不直观,因此我们可以通过方法签名的方式为 此表达式命名。因此Pointcut中的方法只需要方法签名,而不需要在方法体内编写实际代码。
@Around:环绕增强,相当于MethodInterceptor
@AfterReturning:后置增强,相当于AfterReturningAdvice,方法正常退出时执行
@Before:标识一个前置增强方法,相当于BeforeAdvice的功能,相似功能的还有
@AfterThrowing:异常抛出增强,相当于ThrowsAdvice
@After: final增强,不管是抛出异常或者正常退出都会执行

@Pointcut, 定义一个切面,即上面注解中的一个入口切入点定义了时间触发时机

用法:

@Component
@Aspect
// @Order
public class AopAspect {

    @Pointcut("execution(* com.bjpowernode.controller.*.*(..))")
    public void exp(){}

    public static final String POINT_CUT = "execution(* com.bjpowernode.controller.*.*(..))";

    /**
     * 前置通知
     */
    @Before("exp()")
    public void before(){
        System.out.println("切面前置通知...");
    }

    /**
     * 后置通知
     */
    @After(POINT_CUT)
    public void after(){
        System.out.println("切面后置通知...");
    }

    /**
     * returning = "result" 定义返回值参数
     * 返回通知
     */
    @AfterReturning(value = POINT_CUT, returning = "result")
    public void returning(Object result){
        System.out.println("切面返回通知..." + result);
    }

    /**  
     * throwing = "ex" 定义异常参数
     * 异常通知
     */
    @AfterThrowing(value = POINT_CUT, throwing = "ex")
    public void throwing(Exception ex){
        System.out.println("切面异常通知..." + ex.getMessage());
    }
}

14. Swagger

@Api(tags = "学生接口") 用在请求的类上,表示对类的说明

@ApiOperation("分页条件查询学生信息")  对某个方法/接口进行描述
@ApiImplicitParams({
        @ApiImplicitParam(name = "pageNumber", value = "当前页码", required = false, dataType = "Integer", defaultValue = "1", paramType = "query"),
        @ApiImplicitParam(name = "pageSize", value = "每页条数", required = false, dataType = "Integer", defaultValue = "10", paramType = "query")
})
@ApiResponses({
        @ApiResponse(code = 0, message = "成功"),
        @ApiResponse(code = -1, message = "失败")
})

示例:

@RestController
@RequestMapping("/student")
@Api(tags = "学生接口")
public class StudentController  {

        @GetMapping("/page")
        @ApiOperation("分页条件查询学生信息")
        @ApiImplicitParams({
                @ApiImplicitParam(name = "pageNumber", value = "当前页码", required = false, dataType = "Integer", defaultValue = "1", paramType = "query"),
                @ApiImplicitParam(name = "pageSize", value = "每页条数", required = false, dataType = "Integer", defaultValue = "10", paramType = "query")
        })
        @ApiResponses({
                @ApiResponse(code = 0, message = "成功"),
                @ApiResponse(code = -1, message = "失败")
        })
        public Result page(@RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber,
                           @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                           Student student){
                System.out.println(pageNumber);
                System.out.println(pageSize);
                System.out.println(student);
                return Result.success();
        }

        @GetMapping("/get/{id}")
        @ApiOperation("根据ID查询学生信息")
        @ApiImplicitParam(name = "id", value = "学生编号", required = true, dataType = "Integer", paramType = "path")
        public Result get(@PathVariable("id") Integer id){
                System.out.println(id);
                return Result.success();
        }

        @PostMapping("/save")
        @ApiOperation("新增学生信息")
        public Result save(@RequestBody Student student){
                System.out.println(student);
                return Result.success();
        }

        @PutMapping("/update")
        @ApiOperation("编辑学生信息")
        public Result update(@RequestBody Student student){
                System.out.println(student);
                return Result.success();
        }

        @DeleteMapping("/remove/{id}")
        @ApiOperation("根据ID删除学生信息")
        @ApiImplicitParam(name = "id", value = "学生编号", required = true, dataType = "Integer", paramType = "path")
        public Result remove(@PathVariable("id") Integer id){
                System.out.println(id);
                return Result.success();
        }
}

 解释:

@Api:用在请求的类上,表示对类的说明
    tags="说明该类的作用,可以在UI界面上看到的注解"
    value="该参数没什么意义,在UI界面上也看到,所以不需要配置"
 
 
@ApiOperation:用在请求的方法上,说明方法的用途、作用
    value="说明方法的用途、作用"
    notes="方法的备注说明"
 
 
@ApiImplicitParams:用在请求的方法上,表示一组参数说明
    @ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
        name:参数名
        value:参数的汉字说明、解释
        required:参数是否必须传
        paramType:参数放在哪个地方
            · header --> 请求参数的获取:@RequestHeader
            · query --> 请求参数的获取:@RequestParam
            · path(用于restful接口)--> 请求参数的获取:@PathVariable
            · body(不常用)
            · form(不常用)    
        dataType:参数类型,默认String,其它值dataType="Integer"       
        defaultValue:参数的默认值
 
 
@ApiResponses:用在请求的方法上,表示一组响应
    @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
        code:数字,例如400
        message:信息,例如"请求参数没填好"
        response:抛出异常的类
 
 
@ApiModel:用于响应类上,表示一个返回响应数据的信息
            (这种一般用在post创建的时候,使用@RequestBody这样的场景,
            请求参数无法使用@ApiImplicitParam注解进行描述的时候)
    @ApiModelProperty:用在属性上,描述响应类的属性
@ApiModel("学生实体")   //对该接口相关实体类添加额外的描述信息
@ApiModelProperty("学生ID")   //对该接口相关实体类添加额外的描述信息

用法:

@ApiModel("学生实体")
public class Student {

    @ApiModelProperty("学生ID")
    private Integer id;
    @ApiModelProperty("学生姓名")
    private String name;
    @ApiModelProperty("学生地址")
    private String address;
    @ApiModelProperty("学生生日")
    private Date birthday;
}

14 @Transactional(rollbackFor = Exception.class)  //添加事务,作用在类或方法上默认回滚运行异常

15 @Scheduled(cron = "0/5 * * ? * 1-7") // 用在方法上

用这个注解的时候启动类上面要添加

@EnableScheduling //开启定时任务

/**
 * 定时任务注解 @Scheduled cron为定时表达式
 * 秒 分 时 日 月 周 年(可选)
 * *星号:表示每,每秒,每分....
 * ?问好:只能在日期和星期两个位置出现,排除冲突
 * -中划线:表示一个范围
 * ,逗号:表示一个列表值,比如在星期中使用 1,2,4
 */

16 @Async //标记的异步的方法方法上一旦标记了这个方法,当其它线程调用这个方法时,就会开启一个新的线程去异步处理业务逻辑。 上面的配置会启用默认的执行器,异步执行指定的方法。 在业务场景中,有时需要使用自己定义的执行器来跑异步的业务逻辑,那该怎么办呢? 1、 @Async 注解由于是异步执行的,在其调用数据库操作之时,将无法产生事务管理的控制。 解决办法,可以把@Transactional注解放到内部的需要进行事务的方法上

用这个注解的时候启动类上面要添加,

@EnableAsync //开启异步调用

16 redis

@EnableCaching  //用在redis配置类上面

@CachePut(cacheNames = CommonsUtil.USER_LOGIN_CACHE, key = "#username", unless = "#result == null")

        作用:向redis中存放数据,缓存的值为当前方法的返回值

@Cacheable(cacheNames = CommonsUtil.USER_LOGIN_CACHE, key = "#username", unless = "#result == null")

        作用:根据指定key获取redis对应的value,如果在redis查找不到对应value值,就会执行方法,将方法的返回值存储到redis中

@CacheEvict(cacheNames = CommonsUtil.USER_LOGIN_CACHE, key = "#username")

        作用:清除缓存

@CacheEvict(cacheNames = CommonsUtil.USER_LOGIN_CACHE, allEntries = true)

        批量删除缓存:根据缓存的前缀(缓存空间)删除多个缓存

示例:

package com.bjpowernode.serivce;

import com.bjpowernode.bean.User;
import com.bjpowernode.commons.CommonsUtil;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    /**
     * @CachePut
     * 作用:向redis中存放数据
     * 缓存的值为当前方法的返回值
     * redis中的键 = 配置项cacheNames + 配置项key
     *
     * 配置项:
     * cacheNames/value 缓存空间,缓存键的前缀,是属于键中的固定部分,所以指定字符串
     * key 缓存键中动态部分,其中不能使用固定字符串,需要使用表达式来实现
     *      表达式:
     *          #result 表示当前方法的返回值对象
     *          #当前方法参数名(推荐使用)
     *          #root.args 表示当前方法的参数列表(数组)
     *          #root.args[0] 表示当前方法的第一个参数 #a0 #p0
     *          #root.methodName表 示当前方法的名称
     * unless/condition 存储条件,其中必须使用表达式
     *
     */
    @CachePut(cacheNames = CommonsUtil.USER_LOGIN_CACHE, key = "#username", unless = "#result == null")
    public User login(String username, String password){
        //模拟登录
        return new User(1000, username, password);
        // return null;
    }

    /**
     * @Cacheable
     * 作用:根据指定key获取redis对应的value,如果在redis查找不到对应value值,就会执行方法,将方法的返回值存储到redis中
     *
     * 如果只想实现查询的功能,方法返回值为null,并配置存放条件为null值不存储
     */
    @Cacheable(cacheNames = CommonsUtil.USER_LOGIN_CACHE, key = "#username", unless = "#result == null")
    public User getUser(String username){
        System.out.println("getUser.....");
        return new User(111, username, null);
    }

    /**
     * @CacheEvict
     * 作用:清除缓存
     */
    @CacheEvict(cacheNames = CommonsUtil.USER_LOGIN_CACHE, key = "#username")
    public void removeUser(String username){
        System.out.println("删除缓存...");
    }

    /**
     * 批量删除缓存:根据缓存的前缀(缓存空间)删除多个缓存
     */
    @CacheEvict(cacheNames = CommonsUtil.USER_LOGIN_CACHE, allEntries = true)
    public void removeUserAll(){
        System.out.println("删除全部缓存...");
    }
}

17Test模块注解

@RunWith(SpringJUnit4ClassRunner.class),让测试运行于Spring测试环境  @SpringBootTest(classes = SpringbootElasticsearchApp.class),配置Test模块上面的启动类

二.Mybatis-Plus

前提

service层继承IService<实体类类型>类

serviceImpl继承ServiceImpl<持久层接口类型, 实体类类型>类

dao层继承BaseMapper<实体类类型>类

@TableName  描述:表名注解,标识实体类对应的表  使用位置:实体类

@TableId 描述:主键注解  使用位置:实体类主键字段

@TableField 描述:字段注解(非主键)

@TableLogic  描述:表字段逻辑处理注解(逻辑删除) 实体类成员变量

示例:

@Data
@Accessors(chain = true)
@TableName("tab_user")
public class User {

    /**
     * type = IdType.ASSIGN_ID 默认值,表示当前主键值由MybatisPlus生成,采用雪花算法
     * IdType.AUTO MybatisPlus不再生成主键,而是由数据库生成
     */
    @TableId(value = "id", type = IdType.ASSIGN_ID)
    private String userId;
    
    private String name;
    
    private Integer age;
    
    @TableField("email")
    private String userEmail;
    
    private String gender;
    
    //扩容属性,关联属性
    //表示当前属性在表中没有对应字段
    @TableField(exist = false)
    private String genderName;
    
    //标识当前属性对应的逻辑删除标志字段
    @TableLogic
    private String delFlag;
}

三.SpringSecurity

@EnableWebSecurity   SpringSecurity5.0版本之后,无需配置此注解

@EnableGlobalMethodSecurity(prePostEnabled = true) 开启权限使用注解,配置类或启动类上使用

@PreAuthorize @PreAuthorize 在方法调用前进行权限检查

示例:

    // 角色检查
    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/admin/query")
    public String adminQuery(){
        return "admin-query";
    }


    // 权限检查
    @PreAuthorize("hasAuthority('sys:query')")
    @GetMapping("/query")
    public String query(){
        return "系统查询";
    }

@JsonIgnore  json忽略:在进行json字符串转换时忽略此方法

示例:

    /**
     * json忽略:在进行json字符串转换时忽略此方法
     */
    @JsonIgnore
    public String getPassword() {
        return this.userpwd;
    }

四.Dubbo

@EnableDubbo  开启dubbo注解扫描

示例:

@SpringBootApplication
@EnableDubbo//开启dubbo注解扫描
public class DubboxProviderApp {
    public static void main(String[] args) {
        SpringApplication.run(DubboxProviderApp.class,args);
    }
}

@Reference 从zookeeper中找对应的Service类

示例:

@RestController
public class HelloController {

    //@Autowired//从ioc容器中找HelloService
    @Reference//从zookeeper中找HelloService
    private HelloService helloService;

    @RequestMapping("/hello")
    public String hello(){
        System.out.println(helloService.getClass()+"----------------");
        return helloService.hello();
    }
}

五.SpringCloudaAlibaba

@EnableDiscoveryClient   向注册中心注册该服务,并可以获取其他服务的调用地址

作用在启动类上

示例:

@SpringBootApplication
@EnableDiscoveryClient
public class NacosConfigApp {
    public static void main(String[] args) {
        SpringApplication.run(NacosConfigApp.class,args);
    }
}

@RefreshScope  修改配置文件后则重新生成bean,nacos配置文件不用重启实时更新

@LoadBalanced  开启ribbon的负载均衡默认是轮循方式,用于配置类的RestTemplate的方法上

示例:

@Configuration
public class ConfigBean {

    /**
     * 发送rest请求的工具类
     * @return
     */
    @Bean
    @LoadBalanced //开启ribbon负载均衡,默认时轮询策略
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

    //随机方式
    @Bean
    public IRule iRule(){
        return new RandomRule();
    }
}

 @EnableFeignClients    开启feign注解的扫描 用于consumer启动类上面

@FeignClient("服务名字") 获取服务提供者对象用在feign接口上

六、事务

@Transactional(rollbackFor = Exception.class)  //添加事务,作用在类或方法上默认回滚运行异常

@GlobalTransactiona //服务调用服务的时候使用,与传统的事务并不冲突

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值