Spring Boot 常用注解

Spring Web MVC 注解

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

@RequestMapping 将Web请求与请求处理类中的方法进行映射。六个配置属性:

  • value:映射的请求URL或者其别名
  • method:兼容HTTP的方法名
  • params:根据HTTP参数的存在、缺省或值对请求进行过滤
  • header:根据HTTP Header的存在、缺省或值对请求进行过滤
  • consume:设定在HTTP请求正文中允许使用的媒体类型
  • product:在HTTP响应体中允许使用的媒体类型
@Controller
public class DemoController{
	@RequestMapping(value="/test", method= RequestMethod.GET)
	public String test(){
		return "/test";
	}
}

@GetMapping
@PostMapping
@PutMapping
@DeleteMapping

@RequestBody 将请求主体中的参数绑定到对象中

@Valid 注解对请求主体中的参数进行校验

@ControllerAdvice Spring会自动扫描并检测被@ControllerAdvice所标注的类
@ExceptionHandler 用于捕获Controller中抛出的不同类型的异常,从而达到异常全局处理的目的;
@InitBinder 用于请求中注册自定义参数的解析,从而达到自定义请求参数格式的目的;
@ModelAttribute 表示此方法会在执行目标Controller方法之前执行 。通过模型索引名称来访问已经存在于控制器中的model
@ResponseStatus 指定响应所需要的HTTP STATUS。

// 这里@RestControllerAdvice等同于@ControllerAdvice + @ResponseBody
@RestControllerAdvice
public class GlobalHandler {
    private final Logger logger = LoggerFactory.getLogger(GlobalHandler.class);
    // 这里@ModelAttribute("loginUserInfo")标注的modelAttribute()方法表示会在Controller方法之前
    // 执行,返回当前登录用户的UserDetails对象。这里用的是Spring Security
    @ModelAttribute("loginUserInfo")
    public UserDetails modelAttribute() {
        return (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }
    
    // @InitBinder标注的initBinder()方法表示注册一个Date类型的类型转换器,用于将类似这样的2019-06-10
    // 日期格式的字符串转换成Date对象
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    } 
    
    // 这里表示Controller抛出的MethodArgumentNotValidException异常由这个方法处理
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result exceptionHandler(MethodArgumentNotValidException e) {
        Result result = new Result(BizExceptionEnum.INVALID_REQ_PARAM.getErrorCode(),
                BizExceptionEnum.INVALID_REQ_PARAM.getErrorMsg());
        logger.error("req params error", e);
        return result;
    }
    // 这里表示Controller抛出的BizException异常由这个方法处理
    @ExceptionHandler(BizException.class)
    public Result exceptionHandler(BizException e) {
        BizExceptionEnum exceptionEnum = e.getBizExceptionEnum();
        Result result = new Result(exceptionEnum.getErrorCode(), exceptionEnum.getErrorMsg());
        logger.error("business error", e);
        return result;
    }
    // 这里就是通用的异常处理器了,所有预料之外的Exception异常都由这里处理
    @ExceptionHandler(Exception.class)
    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
    public Result exceptionHandler(Exception e) {
        Result result = new Result(1000, "网络繁忙,请稍后再试");
        logger.error("application error", e);
        return result;
    }

}

@RestController
@Validated
public class MyController {
	//在Controller里取出@ModelAttribute标注的方法返回的UserDetails对象
	//@ModelAttribute通过模型索引名称来访问已经存在于控制器中的model
    @PostMapping("/getUserDetails")
    public UserDetails  getUserDetails(@ModelAttribute("loginUserInfo") UserDetails userDetails) {
        return userDetails;
    }

	//在Controller里将date类型转换为yyyy-MM-dd格式
	@PostMapping("/getDate")
    public String getDate(@NotNull Date date) {
        return date.toString;
    }
}

自定义的属性编辑器,重写setAsText,将字符串按照下划线分割成数组

public class StringToListPropertyEditor extends PropertyEditorSupport {

	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		String[] resultArr = null;
		if (!StringUtils.isEmpty(text)) {
			resultArr = text.split("_");
		}
		setValue(resultArr);
	}
}


@RequestMapping("/test")
@Controller
public class StringToListController {

	@InitBinder
	public void myStringToListBinder(WebDataBinder dataBinder) {
		dataBinder.registerCustomEditor(String[].class, new StringToListPropertyEditor());
	}

	//localhost:8080/test/arr?strToListArr=aaaa_bbbbb_cccc
	@RequestMapping(value = "/arr", method = RequestMethod.GET)
	@ResponseBody
	public String myStringToListTest(String[] strToListArr) {
		String result = Arrays.asList(strToListArr).toString();
		return result;
	}
}

@ResponseBody 自动将控制器中方法的返回值写入到HTTP响应中

@PathVariable 是将方法中的参数绑定到请求URI中的模板变量上


@RequestMapping(value="/users/{userId}/test")
public String test(@PathVariable(value="userId") String userId){
	returen userId;
}

@RequestParam 用于将方法的参数与Web请求的传递的参数进行绑定

@CrossOrigin 为请求处理类或请求处理方法提供跨域调用支持

Spring Bean 注解

@ComponentScan 配置Spring需要扫描的被组件注解注释的类所在的包。

  • basePackages属性或者value属性来配置需要扫描的包路径。
  • value属性是basePackages的别名

@Component 标注一个普通的组件类,它没有明确的业务范围,只是通知Spring被此注解的类需要被纳入到Spring Bean容器中并进行管理。

@Service 标注业务逻辑类。与@Component注解一样,被此注解标注的类,会自动被Spring所管理。

@Repository 标注DAO层的数据持久化类。与@Component注解一样,被此注解标注的类,会自动被Spring所管理。

Spring DI注解

@Bean 是告知Spring,被此注解所标注的类将需要纳入到Bean管理工厂中

public class MyBean{
    private void initMethod(){
        System.out.println("自定义初始化方法");
    }
    private void destroyMethod(){
        System.out.println("自定义销毁方法");
    }
}
----------------------------------------------------
@Configuration
public class BeanConfigurer {
    @Bean(name = "MyBean", initMethod = "initMethod", destroyMethod = "destroyMethod")
    public MyBean getMyBean(){
        System.out.println("MyBean构造方法");
        return new MyBean();
    }
}

@Scope 定义@Component标注的类的作用范围以及@Bean所标记的类的作用范围
作用范围有:singleton、prototype、request、session、globalSession或者其他的自定义范围

@Scope(value=ConfigurableBeanFactory.SCOPE_PROPTOTYPE)

@DependsOn 可以配置Spring IoC容器在初始化一个Bean之前,先初始化其他的Bean对象。

@Configuration
public class MyBeanOrder {
    @Bean("first")
    @DependsOn(value = {"second","thrid"})
    public First first(){
        return new First();
    }

    @Bean("second")
    public Second second(){
        return new Second();
    }

    @Bean("thrid")
    public Thrid thrid(){
        return new Thrid();
    }
}

@Autowired

@Primary 当系统中需要配置多个具有相同类型的bean时,@Primary可以定义这些Bean的优先级

@PostConstruct 在Bean被Spring初始化之前需要执行的方法。

@PreDestroy 于标注Bean被销毁前需要执行的方法

ConfigurationProperties 获取配置文件值

jenkins:
  jenkinsUrl: http://{host}:{port}/
  jobUrl: http://{host}:{port}/api/json?pretty=true
  gitUrl: http://{host}:{port}/{path_with_namespace}.git

----------------------------------------------------------
@Data
@Component
@ConfigurationProperties("jenkins")
public class JenkinsConfig {

    private String jenkinsUrl;

    private String jobUrl;

    private String gitUrl;
}    

Spring Boot注解

@SpringBootApplication 被它标注的类中,可以定义一个或多个Bean,并自动触发自动配置Bean和自动扫描组件。此注解相当于@Configuration、@EnableAutoConfiguration和@ComponentScan的组合。

@EnableAutoConfiguration 根据当前类路径下引入的依赖包,自动配置与这些依赖包相关的配置项

@ConditionalOnClass与@ConditionalOnMissingClass 根据是否存在某个类作为判断依据来决定是否要执行某些配置。

@ConditionalOnProperty 根据Spring配置文件中的配置项是否满足配置要求,从而决定是否要执行被其标注的方法


@Bean
@ConditionalOnProperty(name="alipay",havingValue="on")
Alipay alipay(){
 return new Alipay();
}

@ConditionalOnResource 用于检测当某个配置文件存在使,则触发被其标注的方法

@ConditionalOnResource(resources = "classpath:website.properties")
Properties addWebsiteProperties(){
 //...
}

@ConditionalOnWebApplication与@ConditionalOnNotWebApplication 用于判断当前的应用程序是否是Web应用程序

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值