日常学习与工作中常见的注解(上)

57 阅读7分钟

日常学习与工作中常见的注解

在我们使用SpringBoot中比较常见的注解,提供学习时的查阅方便

其中一部分如下

1)@SpringBootApplication

作用: 组合注解,包括了@Configuration、@EnableAutoConfiguration和@ComponentScan三个注解。用于表示SpringBoot应用程序的入口类。

  • @Configuration: 指示这个类是一个配置类,它定义了一个或多个@Bean方法,用于创建和配置Spring应用程序上下文中的Bean。
  • @EnableAutoConfiguration:启⽤Spring Boot的⾃动配置机制,它会⾃动添加所需的依赖项和配置,以 使应⽤程序能够运⾏。
  • @ComponentScan:指示Spring Boot扫描当前包及其⼦包中的所有@Component、@Service、 @Repository和@Controller注解的类,并将它们注册为Spring Bean。

eg:

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

2)@RestController

作⽤:与@Controller类似,但是@RestController会⾃动将返回值转换为JSON格式。

**@RestController是Spring Framework 4.0版本引⼊的⼀个注解,它是@Controller和@ResponseBody的组合注 解。它⽤于标注⼀个类,表示这个类是⼀个RESTful⻛格的控制器,可以处理HTTP请求并返回JSON/XML格式 的响应。 **

@RestController注解⽤于替代原来的@Controller注解,它默认情况下会将控制器⽅法的返回值转换为JSON格 式,并以HTTP响应的⽅式返回给客户端。如果需要返回XML格式的响应,可以使⽤其他注解,如@Produces和 @Consumes。

eg:

@RestController
public class HelloController {
 @GetMapping("/hello")
 public String hello() {
 return "Hello, World!";
 }
}

3)@RequestMapping

作⽤:⽤于映射请求URL和处理⽅法。@RequestMapping是Spring MVC框架中的⼀个核⼼注解,它⽤于映射 HTTP请求和控制器⽅法之间的关系。它可以⽤于类级别和⽅法级别,⽤于指定请求URL和HTTP⽅法(GET、 POST、PUT、DELETE等)。

eg:

@RestController
@RequestMapping("/api")
public class UserController {
 @GetMapping("/users")
 public List<User> getUsers() {
 // 获取⽤户列表
 }
 @PostMapping("/users")
 public void createUser(@RequestBody User user) {
 // 创建新⽤户
 }
 @GetMapping("/users/{id}")
 public User getUserById(@PathVariable Long id) {
 // 根据ID获取⽤户信息
 }
 @PutMapping("/users/{id}")
 public void updateUser(@PathVariable Long id, @RequestBody User user)
{
 // 更新⽤户信息
 }
 @DeleteMapping("/users/{id}")
 public void deleteUser(@PathVariable Long id) {
 // 根据ID删除⽤户
 }
}

4)@GetMapping

作⽤:⽤于映射HTTP GET请求。

eg:

@RestController
@RequestMapping("/api")
public class UserController {
 @GetMapping("/users")
 public List<User> getUsers() {
 // 获取⽤户列表
 }
 @GetMapping("/users/{id}")
 public User getUserById(@PathVariable Long id) {
 // 根据ID获取⽤户信息
 }
}

5)@PostMapping

作⽤:⽤于映射HTTP POST请求。

eg:

@RestController
@RequestMapping("/api")
public class UserController {
 @PostMapping("/users")
 public void createUser(@RequestBody User user) {
 // 创建新⽤户
 }
}

6)@PutMapping

作⽤:⽤于映射HTTP PUT请求。

eg:

@RestController
@RequestMapping("/api")
public class UserController {
 @PutMapping("/users/{id}")
 public void updateUser(@PathVariable Long id, @RequestBody User user) {
 // 更新⽤户信息
 }
}

7)@DeleteMapping

作⽤:⽤于映射HTTP DELETE请求。

eg:

@RestController
@RequestMapping("/api")
public class UserController {
 @DeleteMapping("/users/{id}")
 public void deleteUser(@PathVariable Long id) {
 // 根据ID删除⽤户
 }
}

8)@RequestParam

作⽤:⽤于获取请求参数的值。

eg:

@RestController
@RequestMapping("/api")
public class UserController {
 @GetMapping("/users")
 public List<User> getUsers(@RequestParam("page") int page, @RequestPara
m("size") int size) {
 // 分⻚获取⽤户列表
 }
}

9)@PathVariable

作⽤:⽤于获取URL中的参数值。@PathVariable是Spring MVC框架中的⼀个注解,⽤于将HTTP请求路径中的 变量绑定到控制器⽅法的参数上。

eg:

@RestController
@RequestMapping("/api")
public class UserController {
 @GetMapping("/users/{id}")
 public User getUser(@PathVariable Long id) {
 // 根据ID获取⽤户信息
 }
}

10)@RequestBody

作⽤:⽤于将HTTP请求的主体转换为⽅法的参数。@RequestBody是Spring MVC框架中的⼀个注解,⽤于将 HTTP请求体中的数据绑定到控制器⽅法的参数上。

@RestController
@RequestMapping("/api")
public class UserController {
 @PostMapping("/users")
 public User createUser(@RequestBody User user) {
 // 创建⽤户
 }
}

11)@ResponseBody

作⽤:⽤于将⽅法的返回值转换为HTTP响应的主体。@ResponseBody是Spring MVC框架中的⼀个注解,⽤于 将控制器⽅法的返回值转换为HTTP响应体中的数据。

eg:

@RestController
@RequestMapping("/api")
public class UserController {
 @GetMapping("/users/{id}")
 public User getUser(@PathVariable Long id) {
 // 根据ID获取⽤户信息
 }
}

12)@Autowired

作⽤:⽤于⾃动装配Spring容器中的Bean。

eg:

@Service
public class UserServiceImpl implements UserService {
 @Autowired
 private UserRepository userRepository;
 // 实现UserService接⼝中的⽅法
}

13)@Component

作⽤:⽤于标识⼀个类是Spring容器中的组件。@Component是Spring框架中的⼀个通⽤注解,⽤于标注⼀个 类作为Spring Bean。

eg:

@Component
public class UserServiceImpl implements UserService {
 // 实现UserService接⼝中的⽅法
}

14)@Service

作⽤:⽤于标识⼀个类是Spring容器中的服务组件。@Service是Spring框架中的⼀个注解,⽤于标注⼀个类作 为服务类(Service)。

eg:

@Service
public class UserServiceImpl implements UserService {
 // 实现UserService接⼝中的⽅法
}

15)@Repository

作⽤:⽤于标识⼀个类是Spring容器中的数据访问组件。@Repository是Spring框架中的⼀个注解,⽤于标注⼀ 个类作为数据访问对象(DAO)。

eg:

@Repository
public class UserRepositoryImpl implements UserRepository {
 // 实现UserRepository接⼝中的⽅法
}

16)@Configuration

作⽤:⽤于标识⼀个类是Spring的配置类。@Configuration是Spring框架中的⼀个注解,⽤于标注⼀个类作为 配置类。

eg:

@Configuration
public class AppConfig {
 @Bean
 public UserService userService() {
 return new UserServiceImpl();
 }
 @Bean
 public UserRepository userRepository() {
 return new UserRepositoryImpl();
 }
}

17)@Value

作⽤:⽤于获取配置⽂件中的属性值。@Value是Spring框架中的⼀个注解,⽤于将配置⽂件中的属性值注⼊到 Bean对象中。

eg:

@Component
public class MyComponent {
 @Value("${my.property}")
 private String myProperty;
 // 其他⽅法
}

**这个类使⽤@Component注解标注,表示这个类是⼀个Spring Bean,可以被其他的Spring Bean⾃动装配。 在属性级别上,@Value注解指定了需要注⼊的属性值,这个属性值可以通过${...}的⽅式引⽤配置⽂件中的属性 值。 **

**在这个例⼦中,MyComponent类中的myProperty属性使⽤@Value注解指定了需要注⼊的属性值,Spring会⾃ 动将配置⽂件中名为my.property的属性值注⼊到这个属性中。 **

**@Value注解⽤于注⼊配置⽂件中的属性值,使得开发者可以⽅便地从配置⽂件中获取属性值,并将其注⼊到 Bean对象中。同时,使⽤@Value注解还可以⽅便地处理不同环境下的配置⽂件,如开发环境和⽣产环境的配置 ⽂件。 **

@Value注解是Spring框架中⽐较常⽤的注解之⼀,可以让开发者更加专注于业务逻辑的实现,⽽不必关⼼属性 值的获取和注⼊细节。

18)@Bean

作⽤:⽤于将⼀个⽅法返回的对象注册到Spring容器中。@Bean是Spring框架中的⼀个注解,⽤于将⼀个⽅法 返回的对象注册为⼀个Spring Bean。

eg:

@Configuration
public class AppConfig {
 @Bean
 public UserService userService() {
 return new UserServiceImpl();
 }
 @Bean
 public UserRepository userRepository() {
 return new UserRepositoryImpl();
 }
}

19)@Import

作⽤:⽤于导⼊其他配置类或Bean。

eg:

@Configuration
@Import({AppConfig1.class, AppConfig2.class})
public class AppConfig {
 // 其他⽅法
}

20)@Conditional

作⽤:⽤于根据条件判断是否创建Bean或执⾏配置

eg:

@Configuration
public class AppConfig {
 @Bean
 @Conditional(DatabaseTypeCondition.class)
 public UserRepository userRepository() {
 return new UserRepositoryImpl();
 }
 // 其他⽅法
}

21)@Profile

作⽤:⽤于指定配置的环境,如开发环境、测试环境或⽣产环境。

eg:

@Configuration
public class AppConfig {
 @Bean
 @Profile("dev")
 public UserService userServiceDev() {
 return new UserServiceDevImpl();
 }
 @Bean
 @Profile("prod")
 public UserService userServiceProd() {
 return new UserServiceProdImpl();
 }
 // 其他⽅法
}

22)@PropertySource

作⽤:⽤于指定配置⽂件的位置。@PropertySource是Spring框架中的⼀个注解,⽤于指定⼀组属性⽂件的位 置,从⽽可以在Spring应⽤程序中使⽤这些属性。

eg:

@Configuration
@PropertySource("classpath:application.properties")
public class AppConfig {
 @Autowired
 private Environment environment;
 @Bean
 public UserService userService() {
 return new UserServiceImpl(environment.getProperty("userService.na
me"));
 }
 // 其他⽅法
}

**这个类使⽤@Configuration注解标注,表示这个类是⼀个配置类,⽤于配置应⽤程序的Bean对象。 **

**在类级别上,使⽤@PropertySource注解可以指定⼀个属性⽂件的位置。在这个例⼦中,使⽤@PropertySource 注解指定了⼀个名为application.properties的属性⽂件,它位于classpath下。 **

**在⽅法级别上,使⽤@Bean注解标注⽅法,表示这个⽅法返回⼀个Bean对象。在这个例⼦中,使⽤ Environment对象从属性⽂件中读取属性值,并将这些属性值传递给UserService实例的构造⽅法。 **

**@PropertySource注解⽤于指定⼀组属性⽂件的位置,使得开发者可以在Spring应⽤程序中使⽤这些属性。同 时,使⽤Environment对象可以⽅便地读取属性⽂件中的属性值,并将这些属性值传递给Bean对象的构造⽅法或 属性。 **

@PropertySource注解是Spring框架中⽐较常⽤的注解之⼀,可以让开发者更加灵活地管理和配置Spring Bean。

23)@Qualifier

作⽤:⽤于指定注⼊的Bean的名称。

eg:

@Component
public class UserServiceImpl implements UserService {
 @Autowired
 @Qualifier("userRepositoryImpl")
 private UserRepository userRepository;
 //其他方法
 }

24)@ExceptionHandler

作⽤:⽤于处理异常

eg:

@ControllerAdvice
public class GlobalExceptionHandler {
 @ExceptionHandler(Exception.class)
 public ModelAndView handleException(Exception ex) {
 ModelAndView modelAndView = new ModelAndView();
 modelAndView.addObject("errorMessage", ex.getMessage());
 modelAndView.setViewName("error");
 return modelAndView;
 }
}

**这个类使⽤@ControllerAdvice注解标注,表示这个类是⼀个全局异常处理器。在⽅法级别上,使⽤ @ExceptionHandler注解可以指定⼀个⽅法来处理控制器中抛出的异常。 **

**在这个例⼦中,使⽤@ExceptionHandler注解指定了⼀个名为handleException的⽅法,它处理所有类型的异 常。当控制器中抛出异常时,会调⽤这个⽅法,并将异常对象作为参数传递给这个⽅法。 **

**在这个⽅法中,使⽤ModelAndView对象来封装错误信息,并将视图名称设置为error。最后,返回这个 ModelAndView对象,将错误信息显示到⽤户界⾯上。 **

**@ExceptionHandler注解⽤于处理控制器中抛出的异常,使得开发者可以根据需要灵活地处理异常。同时,使⽤ @ControllerAdvice注解可以将这个异常处理器应⽤于所有的控制器中。 **

@ExceptionHandler注解是Spring框架中⽐较常⽤的注解之⼀,可以让开发者更加灵活地处理控制器中的异常。

25)@ResponseStatus

作⽤:⽤于指定异常的HTTP响应状态码。

eg:

@Controller
public class UserController {
 @GetMapping("/user/{id}")
 @ResponseBody
 @ResponseStatus(HttpStatus.OK)
 public UserDetails getUserDetails(@PathVariable("id") Long id) {
 // 查询⽤户信息
 UserDetails userDetails = userService.getUserDetails(id);
 if (userDetails == null) {
 throw new UserNotFoundException("User not found");
 }
 return userDetails;
 }
 @ExceptionHandler(UserNotFoundException.class)
 @ResponseStatus(HttpStatus.NOT_FOUND)
 @ResponseBody
 public String handleUserNotFoundException(UserNotFoundException ex) {
 return ex.getMessage();
 }
}

...