Spring Boot 常用注解

一、放在类上面,让 Spring 管理这个类

@Component

把这个工具类交给 Spring 管理,别的类可以直接拿来用

类上写法

复制代码
@Component
public class CacheClient {
    public void set(String key, Object value) {
        // 存Redis
    }
}

别的类怎么引用

复制代码
@Service
public class ShopService {
    // 直接引用上面的 CacheClient
    @Autowired
    private CacheClient cacheClient;

    public void save() {
        cacheClient.set("key", "value");
    }
}

@Service

业务类交给 Spring 管理,Controller 可以调用

类上写法

复制代码
@Service
public class ShopService {
    public Shop getById(Long id) {
        // 查询店铺
        return new Shop();
    }
}

别的类怎么引用

复制代码
@RestController
public class ShopController {
    // 引用 Service
    @Autowired
    private ShopService shopService;

    @GetMapping("/shop/{id}")
    public Shop getShop(@PathVariable Long id) {
        return shopService.getById(id);
    }
}

@RestController

接收前端请求,提供接口,不用别人引用它

写法

复制代码
@RestController
@RequestMapping("/shop")
public class ShopController {
    // 前端访问 /shop/1 就会进来
    @GetMapping("/{id}")
    public String test() {
        return "hello";
    }
}

@Mapper

数据库操作接口,Service 里可以调用查库

写法

复制代码
@Mapper
public interface ShopMapper {
    Shop selectById(Long id);
}

别的类怎么引用

复制代码
@Service
public class ShopService {
    @Autowired
    private ShopMapper shopMapper;

    public Shop getById(Long id) {
        return shopMapper.selectById(id);
    }
}

@Configuration

配置类,里面定义工具,别人可以引用

写法

复制代码
@Configuration
public class ThreadPoolConfig {
    @Bean
    public ExecutorService threadPool() {
        return Executors.newFixedThreadPool(10);
    }
}

别的类怎么引用

复制代码
@Service
public class ShopService {
    @Autowired
    private ExecutorService threadPool;
}

二、加在方法上:自动执行

@PostConstruct

对象一创建好,方法自动跑一次

复制代码
@Service
public class ShopService {
    @Autowired
    private CacheClient cacheClient;

    // 项目启动自动执行
    @PostConstruct
    public void preload() {
        System.out.println("启动自动存缓存");
        cacheClient.set("hotShops", "店铺数据");
    }
}

@PreDestroy

项目关闭前自动执行一次

复制代码
@Component
public class MyCleaner {
    @PreDestroy
    public void close() {
        System.out.println("项目关闭,释放资源");
    }
}

三、数据库事务

@Transactional

方法内报错,所有数据库操作全部回滚

复制代码
@Service
public class ShopService {
    @Transactional
    public void update(Shop shop) {
        // 一步错,全部回滚
        mapper.updateById(shop);
    }
}
相关推荐
武子康1 天前
大数据-264 实时数仓-MySQL Binlog配置详解:从原理到实践|数据恢复与主从复制实战
大数据·hadoop·后端
一叶飘零_sweeeet1 天前
深入理解 AQS:从架构到实现,解锁 Java 并发编程的核心密钥
java·aqs
倾颜1 天前
接入 MCP,不一定要先平台化:一次 AI Runtime 的实战取舍
前端·后端·mcp
wechat_Neal1 天前
Golang的车载应用场景
开发语言·后端·golang
Moment1 天前
AI全栈入门指南:一文搞清楚NestJs 中的 Controller 和路由
前端·javascript·后端
GetcharZp1 天前
告别繁琐配置!这款 Go 写的 Web 服务器,凭什么让 Nginx 都不香了?
后端
IT_陈寒1 天前
Python的asyncio把我整不会了,原来问题出在这儿
前端·人工智能·后端
一叶飘零_sweeeet1 天前
深入拆解 Java CAS:从底层原理到 ABA 问题实战
java·cas·并发编程
ai产品老杨1 天前
异构计算时代的视频底座:基于 ZLMediaKit 与 Spring Boot 的 X86/ARM 跨平台架构解析
arm开发·spring boot·音视频
武子康1 天前
大数据-265 实时数仓-Canal MySQL Binlog配置详解:从原理到实践|数据恢复与主从复制实战
大数据·hadoop·后端