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);
    }
}
相关推荐
TDengine (老段)5 分钟前
TDengine 免费版说明
java·大数据·数据库·物联网·时序数据库·tdengine
人间凡尔赛7 分钟前
AI-Native 云原生架构:2026 年从容器编排到智能体编排的范式革命
后端·云原生·架构
码上有光10 分钟前
异常和智能指针
java·大数据·c++·servlet·异常·智能指针
吴声子夜歌17 分钟前
MongoDB 4.x——SpringBoot框架整合
数据库·spring boot·mongodb
IT_陈寒25 分钟前
Vue的响应式让我加班到凌晨3点,原来问题出在这
前端·人工智能·后端
卷无止境25 分钟前
提升 Python 代码健壮性的方法大盘点
后端·python
snow@li27 分钟前
Spring Boot:项目服务器完整部署教程(零基础可直接实操)
服务器·spring boot·后端
卷无止境1 小时前
Python 异常处理:从入门到工程实践
后端·python
AINative软件工程1 小时前
LLM 应用的熔断降级工程实践:Circuit Breaker 不只是重试的升级版
后端·llm·ai编程