SpringCloud项目常用注解

一、@RequestParam 和 @PathVariable

1. 区别

@RequestParam和@PathVariable都能够完成类似的功能,本质上都是用户的输入,只不过输入的部分不同,@PathVariableURL路径部分输入,而@RequestParam请求的参数部分输入。一般来说用@requestparam是用于form表单提交,或者超链接问号传参,而REST风格一定要用@pathVariable。

更明显的是请求路径上的区别,很明显一个是?键值对,一个是 /参数:@PathVariable主要用于接收http://host:port/path/{参数值}数据,而@RequestParam主要用于接收http://host:port/path?参数名=参数值数据,这里后面也可以不跟参数值。

使用@PathVariable报错: PathVariable annotation was empty on param 0

2. @RequestBody

@RequestBody,作用:在Controller层方法形参上使用,把请求的json格式数据,转换成java对象。


二、@Param注解

@Param是MyBatis所提供的,所属包为 org.apache.ibatis.annotations.Param,作为dao层的注解,作用是用于传递参数,从而可以与SQL中的的字段名相对应。

public List<Role> findRoleByAnnotation(@Param("roleName") String roleName, @Param("note") String note);

<select id="findRoleByMap" parameterType="map" resultType="role">
    select id,name from t_role
    where roleName = #{roleName}
    and note = #{note}
<select>

三、@DateTimeFormat 和 @JsonFormat
  • 注解@DataTimeFormat主要是前后到后台的时间格式转换,如将String转化成Date;

  • 注解@JsonFormat主要是后台到前台的时间格式转换,将Date类型数据转化为指定的日期Json格式传给前台。

@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime updateTime;

@DateTimeFormat 和 @JsonFormat 注解


四、@MapperScan 和 @Mapper

@Mapper一般用在mapper接口上,当使用 @Mapper时,Mybatis 会有一个拦截器,会自动的把 使用@Mapper 注解的接口生成动态代理类。

@Mapper注解针对的是一个个的类,对应于一个个的 Mapper.xml 文件。而很多个mapper接口都要使用 @Mapper太麻烦了,于是 @MapperScan 就应用而生了。@MapperScan 配置一个或多个包路径,自动的扫描这些包路径下的类,自动为它们生成代理类。

当使用了 @MapperScan 注解,将会生成 MapperFactoryBean, 如果没有标注@MapperScan 也就是没有 MapperFactoryBean 的实例,就走 @Import 里面的配置,具体可以在 AutoConfiguredMapperScannerRegistrar 和 MybatisAutoConfiguration 类中查看源代码进行分析。


五、@Valid注解

1. 概念

@Valid注解所属包为:javax.validation.Valid,主要用于表单验证(校验传参是否符合要求),减轻了代码量

所需依赖:

<!-- 可使用validate注解在service层做参数校验 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

'org.springframework.boot:spring-boot-starter-web'依赖中也包含javax.validation.Valid

Controller层,在方法要校验的参数上添加@Valid注解:

@RestController
@RequestMapping("/user")
public class TestController {

    @PostMapping("/save")
    public void save(@Valid @RequestBody UserVo userVo){
       ......
    }
}

在相关实体类的相关字段添加用于充当验证条件的注解:

public class UserVo {
	
	@NotBlank(message = "用户名不能为空")
	private String username;
	@Size(min = 6, max = 12, message = "密码长度设置须为6位到12位")
	private String password;
}

2. 补充(全局异常捕捉类)

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    private final static String EXCEPTION_MSG_KEY = "Exception message : ";

    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleValidException(MethodArgumentNotValidException e){
        //日志记录错误信息
        log.error(Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage());
        //将错误信息返回给前台
        return Result.error(103, Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage());
    }
}

3. @Valid注解类型

参数限制注解说明
@Null限制只能为null
@NotNull限制必须不为null
@NotEmpty验证注解的元素值不为null,且不为空(字符串长度不为0、集合大小不为0)
@NotBlank验证注解的元素值不为null,且不为空(去除首位空格后长度不为0)
@Max(value)限制必须为一个不大于指定值的数字
@Min(value)限制必须为一个不小于指定值的数字
@Size(max,min)限制字符长度必须在min到max之间
@DecimalMax(value)限制必须为一个不大于指定值的数字
@DecimalMin(value)限制必须为一个不小于指定值的数字
@Digits(integer,fraction)限制必须为一个小数
@Future限制必须是一个将来的日期
@Past限制必须是一个过去的日期
@Pattern(value)限制必须符合指定的正则表达式
@Email验证注解的元素值是email,通过正则表达式或flag指定自定义的email格式
  • 不同于@NotEmpty@NotBlank只应用于字符串且在比较时会去除字符串的空格;

  • @Digits(integer,fraction):整数部分位数不能超过integer,小数部分位数不能超过fraction;

  • @Valid注解是什么?


六、@Configuration 和 @Bean

1. 概念

之前Spring一直用的xml配置文件比较多,现在发现新公司用的注解比较多。也就是通过定义一个配置类(以@Configuration注解的类)内部在方法上通过@Bean 注解来完成Bean的依赖注入Spring容器。用注解来配置的话,其实就是减少了配置文件的工作,但总体来说代码可读性其实是会下降的,不过也省去了一大堆的xml配置文件。

2. @Configuration和@Bean

@Configuration

  • @Configuration注解底层是含有@Component ,所以@Configuration的作用和@Component 类似;

  • @Configuration注解相当于Spring xml配置文件中的<beans>标签,里面可以配置bean。

@Bean

  • @Bean注解相当于Spring xml配置文件中的<bean>标签,告诉容器注入一个bean;

  • 用@Bean注解的方法会实例化、配置并初始化返回一个新的对象,这个对象会由Spring IoC 容器管理;

  • @Bean注解的方法上如果没通过bean指定实例名,默认实例名与方法名相同;

  • @Bean注解默认为单例模式,可以通过@Scope(“prototype”)设置为多例。

配置类使用:

@Configuration
public class AppConfig{

    @Bean
    public MyService myService(){
        return new MyServiceImpl();
    }
}

相当于配置文件中:

<beans>
    <bean id="myService" class="com.wfxuni.services.MyServiceImpl">
</beans>

@Configuration@Component的区别在于@Configuration配置类中上一个方法注入的bean可以被下一个方法获取使用:

@Configuration
public class ExampleConfiguration{

    @Bean
    public DataSource dataSource(){
        return new BasicDataSource();
    }

    @Bean
    public PlatformTransactionManager transactionManager(){
        //直接调用上面的方法,在@Configuration中是使用上个方法注入的Bean而不是执行方法返回的新对象。
        return new DataSourceTransactionManager(dataSource());
    }
}

Bean注解的作用之一就是能够管理第三方jar包内的类到容器中, 例如引入一个第三方的jar包,这其中的某个类StringUtil需要注入到我们的IndexService类中,因为我们没有源码,不能在StringUtil中增加@Component或者@Service注解。这时就可以通过使用@Bean的方式,把这个类交到Spring容器进行管理,最终就能够被注入到IndexService实例中。在@Configuration中被@Bean标记的方法,会被Spring进行CGLIB代理,从而进行增强。对于@Bean标记的方法,返回的都是一个bean,在增强的方法中,Spring会先去容器中查看一下是否有这个bean的实例了,如果有了的话,就返回已有对象,没有的话就创建一个,然后放到容器中。

3. Redis哨兵模式配置类(示例):

@Configuration
public class RedisConfiguration {

    @Bean
    @ConditionalOnMissingBean(RedisProperties.class)
    public RedisProperties redisProperties() {
        return new RedisProperties();
    }

    @Bean
    @ConditionalOnMissingBean(JedisPool.class)
    public JedisPool jedisPoolFactory(RedisProperties redisProperties) {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(redisProperties.getRedisMaxTotal());
        poolConfig.setMaxIdle(redisProperties.getRedisMaxIdel());
        poolConfig.setMaxWaitMillis(redisProperties.getRedisMaxwaitmills() * 1000);
        JedisPool jedisPool = new JedisPool(poolConfig, redisProperties.getRedisHost(), Integer.valueOf(redisProperties.getRedisPort()),
                15 * 1000, redisProperties.getRedisPassword(), 0);
        return jedisPool;
    }

    @Bean
    @ConditionalOnMissingBean(JedisPoolConfig.class)
    public JedisPoolConfig jedisPoolConfig(RedisProperties redisProperties) {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(redisProperties.getRedisMaxIdel());
        jedisPoolConfig.setMaxTotal(redisProperties.getRedisMaxTotal());
        jedisPoolConfig.setMinIdle(redisProperties.getRedidMinIdel());
        jedisPoolConfig.setMaxWaitMillis(redisProperties.getRedisMaxwaitmills());
        jedisPoolConfig.setTestWhileIdle(true);
        return jedisPoolConfig;
    }

    @Bean
    @ConditionalOnMissingBean(JedisConnectionFactory.class)
    public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig jedisPoolConfig, RedisProperties redisProperties, RedisSentinelConfiguration redisSentinelConfiguration) {
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(redisSentinelConfiguration);
        jedisConnectionFactory.setPassword(redisProperties.getRedisPassword());
        jedisConnectionFactory.setPoolConfig(jedisPoolConfig);
        return jedisConnectionFactory;
    }


    @Bean
    @ConditionalOnMissingBean(name = "redisTemplate")
    public RedisTemplate<Object, Object> redisTemplate(JedisConnectionFactory jedisConnectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        //开启事务
        template.setEnableTransactionSupport(true);
        template.setConnectionFactory(jedisConnectionFactory);
        //key使用字符串序列化
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);

        //解决value序列化方式
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

    @Bean
    @ConditionalOnMissingBean(RedisSentinelConfiguration.class)
    public RedisSentinelConfiguration redisSentinelConfiguration(RedisProperties redisProperties) {
        Set<String> sentinelHostAndPorts = new HashSet<>();
        sentinelHostAndPorts.add(redisProperties.getRedisSentinelNode1());
        sentinelHostAndPorts.add(redisProperties.getRedisSentinelNode2());
        sentinelHostAndPorts.add(redisProperties.getRedisSentinelNode3());
        return new RedisSentinelConfiguration(redisProperties.getRedisMasterName(), sentinelHostAndPorts);
    }

}

七、@ConfigurationProperties注解

propertites.yml

#指定端口号
spring:
 profiles:
   active: dev
com.tina.username: tina
com.tina.password: 123456

TinaConfig.java

//可以注入在application.properties配置文件中的属性
@ConfigurationProperties(value = "com.tina")
@Component
@Data
public class TinaConfig {

    private String username;
    private String password;
}

八、@JSONField注解
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值