Spring Boot中常用的注解

Spring Boot中使用的注解非常多,以下是一些常见的注解:

@SpringBootApplication:标识主程序类,说明这是一个Spring Boot应用。

@RestController:标识一个控制器类,控制器类中的方法返回的数据通常以JSON格式响应给客户端。

@Autowired:自动装配,用于注入依赖。

@Value:用于读取配置文件中的值,可以使用SpEL表达式。

@RequestMapping:映射请求地址,确定请求处理方法。

@Component、@Service、@Repository:标识组件,用于注册bean。

@Transactional:标识事务。

@Async:标识异步任务。

@EnableAutoConfiguration:启用自动配置。

@ConfigurationProperties:启用属性配置。

以上是Spring Boot开发中常见的一些注解。

我们来演示压下SpringBoot中常用的注解的用法:

@SpringBootApplication: 标识这是一个SpringBoot应用的入口类。

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

@RestController: 标识这是一个RESTful控制器。

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

@RequestMapping: 标识这是一个请求映射。

@RestController
@RequestMapping("/users")
public class UserController {
    @GetMapping("/{id}")
    public User getUser(@PathVariable("id") Long id) {
        return new User(id, "User" + id);
    }
}

@Autowired: 自动注入。

@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    public User getUser(@PathVariable("id") Long id) {
        return userService.getUser(id);
    }
}

@Service: 标识这是一个服务类。

@Service
public class UserService {
    public User getUser(Long id) {
        return new User(id, "User" + id);
    }
}