Spring Boot开发中常用的注解详解

本文详细介绍了SpringBoot中常用的控制器相关注解,如@RestController、@RequestMapping及其子注解,参数绑定、自动装配、事件监听和定时任务等,展示了如何通过注解简化开发和提高代码可维护性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

控制器相关注解

  1. @RestController: 将类标记为RESTful风格的控制器,省去使用@Controller@ResponseBody的组合,自动将返回值绑定到HTTP响应体上。
@RestController
public class MyController {
    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, World!";
    }
}
  1. @RequestMapping: 将HTTP请求映射到控制器方法,可以通过method属性指定处理请求的HTTP方法。
@RestController
@RequestMapping("/api")
public class MyController {
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String sayHello() {
        return "Hello, World!";
    }
}
  1. @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping: 这些注解是@RequestMapping的快捷方式,分别指定处理HTTP GET、POST、PUT、DELETE和PATCH请求的方法。
@RestController
public class MyController {
    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, World!";
    }

    @PostMapping("/create")
    public String create() {
        // 创建资源的逻辑
    }

    @PutMapping("/update")
    public String update() {
        // 更新资源的逻辑
    }

    @DeleteMapping("/delete")
    public String delete() {
        // 删除资源的逻辑
    }

    @PatchMapping("/patch")
    public String patch() {
        // 部分更新资源的逻辑
    }
}

参数绑定注解

  1. @PathVariable: 从URL路径中获取变量值,并将其作为方法参数传递。
@RestController
public class MyController {
    @GetMapping("/hello/{name}")
    public String sayHello(@PathVariable String name) {
        return "Hello, " + name + "!";
    }
}
  1. @RequestParam: 从HTTP请求中获取请求参数的值,并将其作为方法参数传递。
@RestController
public class MyController {
    @GetMapping("/hello")
    public String sayHello(@RequestParam String name) {
        return "Hello, " + name + "!";
    }
}
  1. @RequestBody: 用于接收HTTP请求体的内容,并将其绑定到方法参数上,常用于处理JSON数据。
@RestController
public class MyController {
    @PostMapping("/hello")
    public String sayHello(@RequestBody Person person) {
        return "Hello, " + person.getName() + "!";
    }
}

自动装配和依赖注入注解

  1. @Autowired: 自动装配Spring Bean,可用于构造函数、字段、方法和参数上。
@Service
public class MyService {
    public String getMessage() {
        return "Hello, World!";
    }
}

@RestController
public class MyController {
    @Autowired
    private MyService myService;

    @GetMapping("/hello")
    public String sayHello() {
        return myService.getMessage();
    }
}
  1. @Qualifier: 在存在多个相同类型的Bean时,配合@Autowired使用,指定要注入的Bean名称。
@Service
@Qualifier("english")
public class EnglishGreetingService implements GreetingService {
    public String greet() {
        return "Hello";
    }
}

@Service
@Qualifier("chinese")
public class ChineseGreetingService implements GreetingService {
    public String greet() {
        return "你好";
    }
}

@RestController
public class MyController {
    @Autowired
    @Qualifier("chinese")
    private GreetingService greetingService;

    @GetMapping("/hello")
    public String sayHello() {
        return greetingService.greet() + ", World!";
    }
}
  1. @Primary: 在存在多个相同类型的Bean时,优先选择被标记为@Primary的Bean。
@Service
@Primary
public class EnglishGreetingService implements GreetingService {
    public String greet() {
        return "Hello";
    }
}

@Service
public class ChineseGreetingService implements GreetingService {
    public String greet() {
        return "你好";
    }
}

@RestController
public class MyController {
    @Autowired
    private GreetingService greetingService;

    @GetMapping("/hello")
    public String sayHello() {
        return greetingService.greet() + ", World!";
    }
}

组件和配置相关注解

  1. @Component: 将Java类标记为Spring管理的组件,Spring Boot会自动扫描并将其注册为Bean。
@Component
public class MyComponent {
    public void doSomething() {
        // ...
    }
}
  1. @Service: 声明为服务类的组件注解,通常用于业务逻辑层。
@Service
public class MyService {
    public String getMessage() {
        return "Hello, World!";
    }
}
  1. @Repository: 声明为数据访问层的组件注解,通常用于数据库访问。
@Repository
public class MyRepository {
    public String getData() {
        return "Hello, World!";
    }
}
  1. @Configuration: 声明配置类,配合@Bean使用,提供自定义Bean的创建。
@Configuration
public class MyConfiguration {
    @Bean
    public MyService myService() {
        return new MyService();
    }
}
  1. @Bean: 在@Configuration类中声明方法,返回一个Bean实例,供Spring容器管理。
@Configuration
public class MyConfiguration {
    @Bean
    public MyService myService() {
        return new MyService();
    }

    @Bean
    public MyRepository myRepository() {
        return new MyRepository();
    }
}
  1. @Value: 从属性文件或环境变量中获取值,并将其注入到Spring Bean中。
@Component
public class MyComponent {
    @Value("${app.name}")
    private String appName;

    public void displayAppName() {
        System

.out.println("App Name: " + appName);
    }
}

条件化注解和异步注解

  1. @Conditional: 根据指定的条件判断是否创建Bean,可用于灵活配置Bean的创建过程。
@Configuration
public class MyConfiguration {
    @Bean
    @Conditional(MyCondition.class)
    public MyService myService() {
        return new MyService();
    }
}
  1. @Async: 将方法标记为异步执行,Spring Boot会使用线程池异步地执行该方法。
@Service
public class MyService {
    @Async
    public CompletableFuture<String> doSomethingAsync() {
        // 异步执行的业务逻辑
        return CompletableFuture.completedFuture("Hello, World!");
    }
}

自动配置和属性相关注解

  1. @EnableAutoConfiguration: 启用Spring Boot的自动配置机制,根据classpath中的依赖自动配置Spring Bean。
@SpringBootApplication
@EnableAutoConfiguration
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}
  1. @EnableConfigurationProperties: 启用@ConfigurationProperties注解标记的属性类,将其与配置文件绑定。
@Configuration
@EnableConfigurationProperties(MyProperties.class)
public class MyConfiguration {
    // 配置类的逻辑
}
  1. @Profile: 根据指定的配置文件激活不同的Bean。
@Service
@Profile("dev")
public class DevService implements GreetingService {
    public String greet() {
        return "Hello, Dev!";
    }
}

@Service
@Profile("prod")
public class ProdService implements GreetingService {
    public String greet() {
        return "Hello, Prod!";
    }
}

@RestController
public class MyController {
    @Autowired
    private GreetingService greetingService;

    @GetMapping("/hello")
    public String sayHello() {
        return greetingService.greet();
    }
}

事件处理和定时任务注解

  1. @EventListener: 监听Spring事件的注解,用于处理自定义的事件逻辑。
@Component
public class MyEventListener {
    @EventListener
    public void handleMyEvent(MyEvent event) {
        // 处理自定义事件的逻辑
    }
}

@Component
public class MyEventPublisher {
    @Autowired
    private ApplicationEventPublisher eventPublisher;

    public void publishEvent() {
        MyEvent event = new MyEvent("Hello, World!");
        eventPublisher.publishEvent(event);
    }
}
  1. @Scheduled: 将方法标记为定时任务,可定期执行指定的方法。
@Component
public class MyScheduledTask {
    @Scheduled(fixedRate = 5000) // 每隔5秒执行一次
    public void doSomething() {
        // 定时任务的逻辑
    }
}

缓存相关注解

  1. @Cacheable: 标记方法的结果可以被缓存,下次调用时直接从缓存中获取结果。
@Service
public class MyService {
    @Cacheable("dataCache")
    public String getDataFromDatabase(String key) {
        // 从数据库中获取数据的逻辑
        return data;
    }
}

事务注解

  1. @Transactional: 标记方法需要在事务环境下执行,确保事务的一致性和完整性。
@Service
public class MyService {
    @Transactional
    public void updateData(String data) {
        // 更新数据库的逻辑
    }
}

结论

在Spring Boot开发中,注解是非常重要的组成部分,它们简化了开发过程,提高了代码的可读性和可维护性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值