Spring和Spring Boot常用注解介绍及使用

Spring和Spring Boot框架通过丰富的注解集简化了Java开发,使得配置更加简洁且易于理解。

下面是一些常用的Spring和Spring Boot注解及其使用方式的简介:

目录

1. @Component

2. @Service

3. @Repository

4. @Controller

5. @RestController

6. @Autowired

7. @Value

8. @Configuration

9. @Bean

10. @SpringBootApplication

11. @EnableAutoConfiguration

12. @ComponentScan

13. @Conditional

14. @Profile

15. @Scope

16. @Lazy

17. @PostConstruct 和 @PreDestroy


1. @Component

概述: @Component是一个通用的Spring管理的Bean注解。

使用场景: 任何Spring管理的组件都可以使用@Component,但通常使用其特化注解(如@Service@Repository@Controller)来更明确地表达组件的角色。

@Component
public class MyComponent {
    public void doSomething() {
        System.out.println("Doing something...");
    }
}

2. @Service

概述: @Service@Component的特化,专门用于标识服务层的组件。

使用场景: 标识业务逻辑层的组件,表明该类承担业务服务功能。

@Service
public class MyService {
    public void performService() {
        System.out.println("Performing service...");
    }
}

3. @Repository

概述: @Repository@Component的特化,通常用于数据访问层。

使用场景: 用于DAO层,表明该类负责数据库操作,并启用自动异常转换。

@Repository
public class MyRepository {
    public void save() {
        System.out.println("Saving data...");
    }
}

4. @Controller

概述: @Controller@Component的特化,标识Spring MVC的控制器类。

使用场景: 用于标识控制器类,处理HTTP请求并返回视图。

@Controller
public class MyController {
    @GetMapping("/hello")
    @ResponseBody
    public String sayHello() {
        return "Hello, World!";
    }
}

5. @RestController</

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值