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