Spring Boot 常用注解

2022-08-29  本文已影响0人  一滴矿泉水

简介

SpringBoot基于Spring4.0设计,不仅继承了Spring框架原有的优秀特性,而且还通过简化配置来进一步简化了Spring应用的整个搭建和开发过程。SpringBoot 里面提供了大量的注解用于快速开发,而且非常简单,基本可以做到开箱即用!

注解

截屏2022-08-29 上午10.43.13.png
1、SpringMVC 相关注解

@Controller
@RequestMapping("api")
public class LoginController {
/**
* 登录请求,post请求协议,请求参数数据格式为json
* @param request
*/
@RequestMapping(value = "login", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity login(@RequestBody UserLoginDTO request){
//...业务处理
return new ResponseEntity(HttpStatus.OK);
}
}

@RestController
@RequestMapping("api")
public class LoginController {
/**
* 登录请求,post请求协议,请求参数数据格式为json
* @param request
*/
@RequestMapping(value = "login", method = RequestMethod.POST)
public ResponseEntity login(@RequestBody UserLoginDTO request){
//...业务处理
return new ResponseEntity(HttpStatus.OK);
}
}

/**
*登录请求,post请求协议,请求参数数据格式为表单
*/
@RequestMapping(value = "login", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity login(@RequestParam(value = "userName",required = true) String userName,
@RequestParam(value = "userPwd",required = true) String userPwd){
//...业务处理
return new ResponseEntity(HttpStatus.OK);
}

/**
*restful风格的参数请求
*@param id
*/
@RequestMapping(value = "queryProduct/{id}", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity queryProduct(@PathVariable("id") String id){
//...业务处理
return new ResponseEntity(HttpStatus.OK);
}

@GetMapping("get")
public ResponseEntity get(){
return new ResponseEntity(HttpStatus.OK);
}

@PostMapping("post")
public ResponseEntity post(){
return new ResponseEntity(HttpStatus.OK);
}

@PutMapping("put")
public ResponseEntity put(){
return new ResponseEntity(HttpStatus.OK);
}

@DeleteMapping("delete")
public ResponseEntity delete(){
return new ResponseEntity(HttpStatus.OK);
}

2、Bean 相关注解

@Service
public class DeptService {
//具体的方法
}

@Component
public class DeptService {
//具体的方法
}

@Repository
public interface RoleRepository extends JpaRepository<Role,Long> {
//具体的方法
}

为什么现在使用的很少呢?
主要是因为当我们配置服务启动自动扫描dao层包时,Spring会自动帮我们创建一个实现类,然后注入到bean容器里面。当某些类无法被扫描到时,我们可以显式的在数据持久类上标注@Repository注解,Spring会自动帮我们声明对象。

@Configuration
public class AppConfig {
//相当于 xml 中配置 Bean
@Bean
public Uploader initFileUploader() {
return new FileUploader();
}
}

@Autowired
private DeptService deptService;

/**
通过名称导入(默认通过名称导入依赖对象)
/
@Resource(name = "deptService")
private DeptService deptService;
/

*通过类型导入
*/
@Resource(type = RoleRepository.class)
private DeptService deptService;

@Autowired
@Qualifier("deptService")
private DeptService deptService;

/**
*单例对象
*/
@RestController
@Scope("singleton")
public class HelloController {
}

3、JPA 相关注解

@Entity
@Table(name = "TB_ROLE")
@SequenceGenerator(name = "id_seq", sequenceName = "seq_repair",allocationSize = 1)
public class Role implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键ID,采用【id_seq】序列函数自增长
/
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "id_seq")
private Long id;
/
角色名称
/
@Column(nullable = false)
private String roleName;
/
*
* 角色类型
*/
@Column(nullable = false)
private String roleType;
}

/**
*忽略该属性
*/
@Column(nullable = false)
@Transient
private String lastTime;

/**
*延迟加载该属性
*/
@Column(nullable = false)
@Basic(fetch = FetchType.LAZY)
private String roleType;

@Entity
@Table(name = "tb_login_log")
public class LoginLog implements Serializable {
/**
*查询登录的用户信息
*/
@OneToOne
@JoinColumn(name = "user_id")
private User user;
//...get、set
}

@Entity
@Table(name="address")
public class AddressEO implements java.io.Serializable {
@ManyToOne(cascade = { CascadeType.ALL })
@JoinColumn(name="customer_id")
private CustomerEO customer;
//...get、set
}

4、配置相关注解

@Configuration
public class AppConfig {
@Bean
public Uploader initOSSUploader() {
return new OSSUploader();
}
}

@Configuration
@EnableAutoConfiguration(exclude = { org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration.class
})
public class AppConfig {
//具有业务方法
}

@ComponentScan(basePackages = {"com.xxx.a", "com.xxx.b", "com.xxx.c"})

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

把@SpringBootApplication换成@Configuration、@EnableAutoConfiguration、@ComponentScan这三个注解,一样可以启动成功,@SpringBootApplication只是将这三个注解进行了简化!

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

1)@ConditionalOnBean:当某个特定的Bean存在时,配置生效
2)@ConditionalOnMissingBean:当某个特定的Bean不存在时,配置生效
3)@ConditionalOnClass:当Classpath里存在指定的类,配置生效
4)@ConditionalOnMissingClass:当Classpath里不存在指定的类,配置生效
5)@ConditionalOnExpression:当给定的SpEL表达式计算结果为true,配置生效
6)@ConditionalOnProperty:当指定的配置属性有一个明确的值并匹配,配置生效

具体的应用案例如下:

@Configuration
public class ConditionalConfig {
/**
* 当AppConfig对象存在时,创建一个A对象
* @return
/
@ConditionalOnBean(AppConfig.class)
@Bean
public A createA(){
return new A();
}
/
*
* 当AppConfig对象不存在时,创建一个B对象
* @return
/
@ConditionalOnMissingBean(AppConfig.class)
@Bean
public B createB(){
return new B();
}
/
*
* 当KafkaTemplate类存在时,创建一个C对象
* @return
/
@ConditionalOnClass(KafkaTemplate.class)
@Bean
public C createC(){
return new C();
}
/
*
* 当KafkaTemplate类不存在时,创建一个D对象
* @return
/
@ConditionalOnMissingClass(KafkaTemplate.class)
@Bean
public D createD(){
return new D();
}
/
*
* 当enableConfig的配置为true,创建一个E对象
* @return
/
@ConditionalOnExpression("${enableConfig:false}")
@Bean
public E createE(){
return new E();
}
/
*
* 当filter.loginFilter的配置为true,创建一个F对象
* @return
*/
@ConditionalOnProperty(prefix = "filter",name = "loginFilter",havingValue = "true")
@Bean
public F createF(){
return new F();
}
}

config.name=zhangwanglizhao

在任意的bean容器里面,可以通过@Value注解注入参数,获取参数变量值。

@RestController
public class HelloController {
@Value("${config.name}")
private String config;
@GetMapping("config")
public String config(){
return JSON.toJSONString(config);
}
}

config.name=demo_1
config.value=demo_value_1

然后,创建一个 Java 配置类,将参数变量注入即可!

@Component
@ConfigurationProperties(prefix = "config")
public class Config {
public String name;
public String value;
//...get、set
}

最后,在需要使用的地方,通过ioc注入Config对象即可!

@SpringBootApplication
@PropertySource(value = {"test.properties","bussiness.properties"})
public class PropertyApplication {
public static void main(String[] args) {
SpringApplication.run(PropertyApplication.class, args);
}
}

@ImportResource(locations = "classpath:aaa.xml")
@SpringBootApplication
public class PropertyApplication {
public static void main(String[] args) {
SpringApplication.run(PropertyApplication.class, args);
}
}

5、异常处理相关注解

@ControllerAdvice
@Configuration
@Slf4j
public class GlobalExceptionConfig {
private static final Integer GLOBAL_ERROR_CODE = 500;
@ExceptionHandler(value = Exception.class)
@ResponseBody
public void exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception {
log.error("【统一异常处理器】", e);
ResultMsg<Object> resultMsg = new ResultMsg<>();
resultMsg.setCode(GLOBAL_ERROR_CODE);
if (e instanceof CommonException) {
CommonException ex = (CommonException) e;
if(ex.getErrCode() != 0) {
resultMsg.setCode(ex.getErrCode());
}
resultMsg.setMsg(ex.getErrMsg());
}else {
resultMsg.setMsg(CommonErrorMsg.SYSTEM_ERROR.getMessage());
}
WebUtil.buildPrintWriter(response, resultMsg);
}
}

6、测试相关注解

@ActiveProfiles("dev")
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestJunit {
@Test
public void executeTask() {
//测试...
}
}

参考链接:https://zhuanlan.zhihu.com/p/489217499


文章持续更新中、希望对各位有所帮助、有问题可留言 大家共同学习

上一篇下一篇

猜你喜欢

热点阅读