spring注解整理

@CrossOrigin(origins="*.a.cn"):跨域

Hibernate jpa

@PreRemove:删除前,还有更新前等等

mybatis -> entity

@Tableid:自增

@TableField(exist = false):不验证

@NotEmpty(groups = Save.class):指定方法验证

@Lob

@JsonValue

@JsonIgnore 此注解用于属性上,作用是进行JSON操作时忽略该属性。
@JsonFormat 此注解用于属性上,作用是把Date类型直接转化为想要的格式,如@JsonFormat(pattern = “yyyy-MM-dd HH-mm-ss”)。
@JsonProperty 此注解用于属性上,作用是把该属性的名称序列化为另外一个名称,如把trueName属性序列化为name,@JsonProperty(“name”)。

@PathVariable 

@GetMapping("/detail/{promotionId}")
    public String detail(@PathVariable Long promotionId, ModelMap model) {

取占位符值

@JsonView:不同方法返回不同的值

@ModelAttribute:返回前先调用这个方法,增加返回参数时可以使用

@IgnoreAuth:忽略权限

1、@Autowired是spring自带的,@Inject是JSR330规范实现的,@Resource是JSR250规范实现的,需要导入不同的包

2、@Autowired、@Inject用法基本一样,不同的是@Autowired有一个request属性

3、@Autowired、@Inject是默认按照类型匹配的,@Resource是按照名称匹配的

4、@Autowired如果需要按照名称匹配需要和@Qualifier一起使用,@Inject和@Name一起使用

在这里插入图片描述

lombok@Data:生成getter,setter ,toString等函数
lombok@Builder:生成任意组合参数的构造方法(使用构造者模式实现)
lombok@NoArgsConstructor:生成无参构造函数
lombok@AllArgsConstructor:解决Builder和NoArgsConstructor冲突

lombok@Slf4j

private  final Logger logger = LoggerFactory.getLogger(当前类名.class);

Feign@FeignClient(name = "user-service",contextId = "user-service-BusinessObjectFieldsService")

feign注解,feign调用注册中心名字为user-service的服务对应同名同参方法,contexid防止名字重复的别名

spring@Component(value="")

@Controller控制层@Service()@Repository持久层

配置在类或接口上,相当于<bean id="userAnnonMapper" class="com.spring.mapper.UserAnnonMapperImpl"></bean>,注解Value属性:相当于bean标签id,对象在IOC容器中的唯一标识,可以不写,默认值是当前类
首字母缩写的类名。注入时需要注意此名称

spring@RequestMapping(path = "/businessObjectFields/list", method = RequestMethod.POST)

mapping映射路径

HTTP请求报文解剖

form表单中enctype 属性可以设置下面三种

Http Header里的Content-Type一般有这三种:

  1. application/x-www-form-urlencoded:数据被编码为名称/值对。这是标准的编码格式。
  2. multipart/form-data: 数据被编码为一条消息,页上的每个控件对应消息中的一个部分。
  3. text/plain: 数据以纯文本形式(text/json/xml/html)进行编码,其中不含任何控件或格式字符。postman软件里标的是RAW。

2.请求头部

请求头部是 字段名:值 的格式展现

用于HTTP请求中的常用请求头字段
Accept:       用于高速服务器,客户机支持的数据类型
Accept-Charset:  用于告诉服务器,客户机采用的编码格式
Accept-Encoding:用于告诉服务器,客户机支持的数据压缩格式
Accept-Language:客户机的语言环境
Host:      客户机通过这个头高速服务器,想访问的主机名
If-Modified-Since:客户机通过这个头告诉服务器,资源的缓存时间
Referer:      客户机通过这个头告诉服务器,它是从哪个资源来访问服务器的(防盗链)
User-Agent:    客户机通过这个头告诉服务器,客户机的软件环境
Cookie:       客户机通过这个头可以向服务器带数据
Connection:    处理完这次请求后是否断开连接还是继续保持连接
Date:        当前时间值

2.响应头

响应头通常也是由 字段名:值  组成

响应头用于描述服务器的基本信息,以及数据的描述,服务器通过这些数据的描述信息,可以通知客户端如何处理等一会儿它回送的数据。

常见的响应头字段:

Location:         这个头配合302状态码使用,用于告诉客户找谁。
Server:          服务器通过这个头告诉浏览器服务器的类型。
Content-Encoding: 服务器通过这个头告诉浏览器数据的压缩格式。
Content-Length:  服务器通过这个头告诉浏览器回送数据的长度
Content-Type:     服务器通过这个头告诉浏览器回送数据的类型
Last-Modified:     告诉浏览器当前资源的最后缓存时间
Refresh:          告诉浏览器隔多久刷新一次
Content-Disposition:告诉浏览器以下载方式打开数据
Transfer-Encoding:  告诉浏览器数据的传送格式
ETag:              缓存相关的头

spring@RequestBody

PageInfo<BusinessObjectFields> queryByPage(@RequestBody BusinessObjectFieldsDTO businessObjectFieldsDTO);

接收报文体参数

spring@RequestParam

spring@RequestParam有三个配置参数:

  • required 表示是否必须,默认为 true,必须。
  • defaultValue 可设置请求参数的默认值。
  • value 为接收url的参数名(相当于key值)。

可以接受报文头参数和报文体为 application/x-www-form-urlencoded的参数

spring@Aspect(配合@Component才有作用)

切面雷

spring@Pointcut("(execution(* com.dawdler.user.controller.business.*.*(..) ))")

切入点

spring@Around(value = "pointcut()")

环切

public Object aroundMethod(ProceedingJoinPoint pdj) throws Throwable {

        String className = pdj.getTarget().getClass().getName();
        String methodName = pdj.getSignature().getName();

Stopwatch otaWatch = Stopwatch.createStarted();
            result = pdj.proceed();//执行
            otaWatch.stop();//计时器


jdk@Retention(RetentionPolicy.RUNTIME)
jdk@Target({ElementType.METHOD})
jdk@Inherited
jdk@Documented

jdk原注解,创建注解用

1.RetentionPolicy.SOURCE —— 这种类型的Annotations只在源代码级别保留,编译时就会被忽略
2.RetentionPolicy.CLASS —— 这种类型的Annotations编译时被保留,在class文件中存在,但JVM将会忽略
3.RetentionPolicy.RUNTIME —— 这种类型的Annotations将被JVM保留,所以他们能在运行时被JVM或其他使用反射机制的代码所读取和使用.

Documented 注解表明这个注解应该被 javadoc工具记录

@Inherited注解的子类自动继承父类

取类注解方法

public void setAnnotatioinFieldValue(String className, String methodName, String annoName, String fieldName, String fieldValue) throws NotFoundException {
        ClassPool classPool = ClassPool.getDefault();
        CtClass ct = classPool.get(className);
        CtMethod ctMethod = ct.getDeclaredMethod(methodName);
        MethodInfo methodInfo = ctMethod.getMethodInfo();
        ConstPool constPool = methodInfo.getConstPool();
        AnnotationsAttribute attr = (AnnotationsAttribute) methodInfo.getAttribute(AnnotationsAttribute.visibleTag);
        Annotation annotation = attr.getAnnotation(annoName);
        if (annotation != null) {
            annotation.addMemberValue(fieldName, new StringMemberValue(fieldValue, constPool));
            attr.setAnnotation(annotation);
            methodInfo.addAttribute(attr);
        }
    }

swagger@Api("业务对象管理")

@ApiOperation(value = "fieldCombinationRuleList", nickname = "条件关系值下拉框", notes = "条件关系值下拉框")

@ApiResponses({@ApiResponse(code = 404, response = String.class, message = "接口不存在"),
            @ApiResponse(code = 500, response = String.class, message = "程序错误")})

使用在类上,表明是swagger资源,@API拥有两个属性:value、tags

生成的api文档会根据tags分类,直白的说就是这个controller中的所有接口生成的接口文档都会在tags这个list下;tags如果有多个值,会生成多个list,每个list都显示所有接口

swagger@ApiOperation
使用于在方法上,表示一个http请求的操作
源码中属性太多,记几个比较常用
value用于方法描述
notes用于提示内容
tags可以重新分组(视情况而用)

swagger@ApiParam
使用在方法上或者参数上,字段说明;表示对参数的添加元数据(说明或是否必填等)
name–参数名
value–参数说明
required–是否必填

swagger@ApiModel()
使用在类上,表示对类进行说明,用于参数用实体类接收
value–表示对象名
description–描述

swagger@ApiModelProperty()
使用在方法,字段上,表示对model属性的说明或者数据操作更改
value–字段说明
name–重写属性名字
dataType–重写属性类型
required–是否必填
example–举例说明
hidden–隐藏

@ResponseBody

@responseBody注解的作用是将controller的方法返回的对象通过适当的转换器转换为指定的格式之后,写入到response对象的body区,通常用来返回JSON数据或者是XML数据。
注意:在使用此注解之后不会再走视图处理器,而是直接将数据写入到输入流中,他的效果等同于通过response对象输出指定格式的数据。
原文链接:https://blog.csdn.net/originations/article/details/89492884

spring@RestController

@Controller+@ResponseBody

@RestController
public class BusinessObjectController {

Spring Cloud@EnableDiscoveryClient

eureka@EnableEurekaClient

开启服务注册

@EnableDiscoveryClient

public class UserControllerApplication

spring@Autowired

自动注入

@Autowired
    private BusinessObjectService businessObjectService;

spring@Validated

家在验证的BEAN,开启验证

public Result<PageInfo<BusinessObject>> list(@Validated @NotNull @RequestBody BusinessObjectQueryParam businessObjectQueryParam) {

然后在BEAN对应字段上加如下注解

spring@ControllerAdvice 三个功能:

@ControllerAdvice
class GlobalControllerExceptionHandler 

  1. 全局异常处理
  2. 全局数据绑定
  3. 全局数据预处理@ExceptionHandler

@ExceptionHandler

返回值支持ModelAndView,@ResponseBody等多种形式.   

@ResponseStatus(HttpStatus.OK)

指定返回码,异常是也可以返回200
    @ResponseBody
    Result handleException(MethodArgumentNotValidException ex) {
        log.debug("Validate Exception.", ex);
        List<String> messageList = Stream.concat(
                ex.getBindingResult()
                        .getFieldErrors()
                        .stream()
                        .map(i -> i.getField() + ": " + i.getDefaultMessage()),
                ex.getBindingResult()
                        .getGlobalErrors()
                        .stream()
                        .map(i -> i.getObjectName() + ": " + i.getDefaultMessage()))
                .sorted(String::compareTo)
                .collect(Collectors.toList());

        String message = StringUtils.join(messageList, ", ");
        return Result.failure(ResponseState.RESPONSE_SYSTEM_ERROR.code, message);
    }

@ExceptionHandler(value = {AcException.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    Result handleException(AcException ex,String msg) {
        log.error("HttpMessageNotReadableException Error: context:{}", RequestContextHolder.context(), ex);
        return Result.failure(ResponseState.RESPONSE_SYSTEM_ERROR.code, msg);
    }

AcException为自定义异常,继承异常类throw new AcException

spring@Value("${debug}")

取配置文件值

spring@Configuration

spring@bean

配置文件,配合使用

swagger@EnableSwagger2

swagger配置文件

@Configuration
public class SwaggerConfig {

@Bean
    public Docket createRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
    .groupName("")
    .apiInfo(getApiInfo())
    .select()
    .apis(RequestHandlerSelectors.basePackage("com.dawdler.user.controller.business"))
    .paths(PathSelectors.any())
    .build();
    }

private ApiInfo getApiInfo() {
        return new ApiInfoBuilder()
                .title("ac基础架构平台")
                .description("ac基础架构平台")
                .version("v1.0")
                .termsOfServiceUrl("**")
                .contact(new Contact(
                        "ac基础架构平台",
                        "**",
                        "chenyongke@accenture.com"))
                .build();
    }

spring@Profile

数据源:(/dev) (/test) (/master)指定组件在哪个环境下注入

spring@ConditionalOnProperty

通过@ConditionalOnProperty控制配置类是否生效,可以将配置与代码进行分离,实现了更好的控制配置.
@ConditionalOnProperty实现是通过havingValue与配置文件中的值对比,返回为true则配置类生效,反之失效.

filter.loginFilter=true

@ConditionalOnProperty(prefix = "filter",name = "loginFilter",havingValue = "true")

spring@Override

重写父类

spring boot@SpringBootApplication

spring boot启动类

@SpringBootApplication(scanBasePackages = {
        "com.dawdler.user.controller.business",
        "com.dawdler.user.controller.annotation",
        "com.dawdler.user.controller.exception",
        "com.dawdler.user.controller.swagger",
        "com.dawdler.user.listener",
        "com.anywide.dawdler.clientplug.web.session"},

@ComponentScan

这个注解在Spring中很重要,它对应XML配置中的元素,@ComponentScan的功能其实就是自动扫描并加载符合条件的组件(比如@Component和@Repository等)或者bean定义,最终将这些bean定义加载到IoC容器中。

我们可以通过basePackages等属性来细粒度的定制@ComponentScan自动扫描的范围,如果不指定,则默认Spring框架实现会从声明@ComponentScan所在类的package进行扫描。

例如,如果你有个类用@Controller注解标识了,那么,如果不加上@ComponentScan,自动扫描该controller,那么该Controller就不会被spring扫描到,更不会装入spring容器中,因此你配置的这个Controller也没有意义。

basePackageClasses:对basepackages()指定扫描注释组件包类型安全的替代。
 
excludeFilters:指定不适合组件扫描的类型。
 
includeFilters:指定哪些类型有资格用于组件扫描。
 
lazyInit:指定是否应注册扫描的beans为lazy初始化。
 
nameGenerator:用于在Spring容器中的检测到的组件命名。
 
resourcePattern:控制可用于组件检测的类文件。
 
scopedProxy:指出代理是否应该对检测元件产生,在使用过程中会在代理风格时尚的范围是必要的。
 
scopeResolver:用于解决检测到的组件的范围。
 
useDefaultFilters:指示是否自动检测类的注释 

@EnableAspectJAutoProxy

开启切面

@EnableFeignClients(basePackages = {"com.dawdler.user.service"})

开启eign

@Transactional

开启事务

mybatis@Mapper

mapper对应的类

mybatis@MapperScan(basePackages = {"com.dawdler.user.service.mapper"})

加在启动类上,指定包下全部生成,相当于@Mappe

mybatis@Param("queryDTO")

注意此时并不需要写出parameterType属性,Mybatis会进行自动搜索。

@ServletComponentScan

在启动类上使用@ServletComponentScan注解后,Servlet、Filter、Listener可以直接通过@WebServlet、@WebFilter、@WebListener注解自动注册,无需其他代码。

@EnableTransactionManagement

在启动类上使用开启事务

@EnableScheduling

在启动类上使用开启定时器

@EnableCaching

在启动类上使用开启定时器开启缓存

Spring自身已经为我们提供了两种CacheManager的实现,一种是基于Java API的ConcurrentMap,另一种是基于第三方Cache实现——Ehcache,如果我们需要使用其它类型的缓存时,我们可以自己来实现Spring的CacheManager接口或AbstractCacheManager抽象类。

@Cacheable(value={"users"}, key="#user.id", condition="#user.id%2==0")

@CachePut("users")//每次都会执行方法,并将结果存入指定的缓存中

@CacheEvict

beforeInvocation属性

       清除操作默认是在对应方法成功执行之后触发的,即方法如果因为抛出异常而未能成功返回时也不会触发清除操作。使用beforeInvocation可以改变触发清除操作的时间,当我们指定该属性值为true时,Spring会在调用该方法之前清除缓存中的指定元素。

   @CacheEvict(value="users", beforeInvocation=true)

allEntries是boolean类型,表示是否需要清除缓存中的所有元素。默认为false,表示不需要。当指定了allEntries为true时,Spring Cache将忽略指定的key。有的时候我们需要Cache一下清除所有的元素,这比一个一个清除元素更有效率。

   @CacheEvict(value="users", allEntries=true)

@Caching

       @Caching注解可以让我们在一个方法或者类上同时指定多个Spring Cache相关的注解。其拥有三个属性:cacheable、put和evict,分别用于指定@Cacheable、@CachePut和@CacheEvict。

   @Caching(cacheable = @Cacheable("users"), evict = { @CacheEvict("cache2"),

         @CacheEvict(value = "cache3", allEntries = true) })

Spring允许我们在配置可缓存的方法时使用自定义的注解,前提是自定义的注解上必须使用对应的注解进行标注。如我们有如下这么一个使用@Cacheable进行标注的自定义注解。

@Target({ElementType.TYPE, ElementType.METHOD})

@Retention(RetentionPolicy.RUNTIME)

@Cacheable(value="users")

public @interface MyCacheable {

}

@SuppressWarnings("unchecked")

忽略警告

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值