一、放在类上面让 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); } }