1. SSM植物养殖购买系统概述
SSM植物养殖购买系统是基于SSM(Spring+SpringMVC+MyBatis)框架开发的一套面向植物养殖行业的电商管理系统。这个系统主要解决了植物养殖行业在销售、库存管理、客户服务等方面的信息化需求,为中小型植物养殖企业提供了一个完整的线上经营解决方案。
作为一个典型的Java Web应用,该系统采用了当前企业级开发中最流行的SSM框架组合。Spring作为核心容器管理着整个应用的Bean生命周期,SpringMVC负责处理Web层的请求分发和响应,而MyBatis则作为持久层框架与数据库进行交互。这种架构组合既保证了系统的稳定性,又提供了良好的扩展性。
系统源码(编号00229)包含了完整的实现代码,涵盖了用户管理、商品管理、订单处理、库存管理等核心模块。对于想要学习SSM框架实际应用的开发者来说,这套源码提供了很好的参考价值。同时,系统采用模块化设计,各功能组件耦合度低,便于二次开发和功能扩展。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 系统架构与技术选型
2.1 SSM框架整合方案
本系统采用标准的SSM框架整合方式,但针对植物养殖行业的特殊需求做了一些定制化调整。在Spring配置方面,我们不仅配置了基本的事务管理和AOP支持,还特别针对植物商品的特点添加了缓存策略:
xml复制<!-- Spring事务管理配置 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 植物商品缓存配置 -->
<bean id="plantCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">
<property name="cacheManager" ref="cacheManager"/>
<property name="cacheName" value="plantCache"/>
</bean>
SpringMVC的配置则着重处理了植物图片上传和展示的特殊需求。我们配置了专门的多部分解析器来处理高清植物图片的上传,并设置了静态资源映射以便快速访问这些图片资源。
MyBatis的映射文件则针对植物商品的各种查询场景做了优化,包括按种类查询、按生长条件查询等复杂查询语句。特别值得一提的是,我们为植物库存管理实现了专门的动态SQL,可以根据不同条件灵活地查询库存状态。
2.2 数据库设计要点
植物养殖系统的数据库设计有几个关键点需要特别注意。首先是商品表的设计,与普通商品不同,植物商品需要记录更多的属性:
sql复制CREATE TABLE `plant_product` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL COMMENT '植物名称',
`category_id` int(11) NOT NULL COMMENT '分类ID',
`price` decimal(10,2) NOT NULL COMMENT '价格',
`stock` int(11) NOT NULL COMMENT '库存数量',
`growth_condition` varchar(255) DEFAULT NULL COMMENT '生长条件要求',
`maturity_period` int(11) DEFAULT NULL COMMENT '成熟周期(天)',
`maintenance_level` tinyint(4) DEFAULT NULL COMMENT '养护难度等级',
`image_url` varchar(255) DEFAULT NULL COMMENT '图片URL',
`description` text COMMENT '详细描述',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP,
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='植物商品表';
其次是订单系统的设计,考虑到植物商品的特殊性,我们增加了养护指导发送状态和植物生长状态跟踪字段:
sql复制CREATE TABLE `plant_order` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`order_no` varchar(32) NOT NULL COMMENT '订单编号',
`user_id` int(11) NOT NULL COMMENT '用户ID',
`total_amount` decimal(10,2) NOT NULL COMMENT '订单总金额',
`payment_status` tinyint(4) NOT NULL DEFAULT '0' COMMENT '支付状态',
`shipping_status` tinyint(4) NOT NULL DEFAULT '0' COMMENT '配送状态',
`care_guide_sent` tinyint(4) NOT NULL DEFAULT '0' COMMENT '养护指导是否发送',
`plant_status` varchar(50) DEFAULT NULL COMMENT '植物生长状态跟踪',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP,
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `idx_order_no` (`order_no`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='植物订单表';
2.3 前端技术选型
虽然系统后端采用SSM框架,但前端技术选型同样重要。本系统采用了Bootstrap作为基础UI框架,确保系统在各种设备上都能良好显示。针对植物图片展示的特殊需求,我们集成了Lightbox插件来实现图片的放大查看功能。
对于更复杂的交互场景,如植物养护日历、生长周期图表等,我们引入了ECharts库来实现数据可视化。这些可视化功能不仅增强了用户体验,也为用户提供了更直观的植物养护信息。
3. 核心功能模块实现
3.1 植物商品管理系统
植物商品管理是系统的核心模块之一,与普通商品管理相比,它需要处理更多特殊属性和业务逻辑。在Controller层,我们设计了完善的RESTful API接口:
java复制@Controller
@RequestMapping("/api/plants")
public class PlantProductController {
@Autowired
private PlantProductService plantProductService;
@GetMapping("/{id}")
@ResponseBody
public Result<PlantProduct> getPlantDetail(@PathVariable Integer id) {
PlantProduct product = plantProductService.getPlantById(id);
return Result.success(product);
}
@PostMapping("/")
@ResponseBody
public Result addPlant(@Valid @RequestBody PlantProduct product) {
plantProductService.addPlant(product);
return Result.success();
}
@GetMapping("/category/{categoryId}")
@ResponseBody
public Result<List<PlantProduct>> getPlantsByCategory(
@PathVariable Integer categoryId,
@RequestParam(required = false) String growthCondition) {
List<PlantProduct> products = plantProductService.getPlantsByCategory(categoryId, growthCondition);
return Result.success(products);
}
}
Service层则实现了更复杂的业务逻辑,特别是植物库存管理部分。我们采用了乐观锁机制来处理并发下的库存更新问题:
java复制@Service
public class PlantProductServiceImpl implements PlantProductService {
@Autowired
private PlantProductMapper plantProductMapper;
@Override
@Transactional
public boolean reduceStock(Integer plantId, Integer quantity) {
// 使用乐观锁机制更新库存
int affectedRows = plantProductMapper.reduceStockWithLock(plantId, quantity);
return affectedRows > 0;
}
@Override
public List<PlantProduct> getPlantsByCategory(Integer categoryId, String growthCondition) {
Map<String, Object> params = new HashMap<>();
params.put("categoryId", categoryId);
if (growthCondition != null && !growthCondition.isEmpty()) {
params.put("growthCondition", growthCondition);
}
return plantProductMapper.selectByConditions(params);
}
}
3.2 智能推荐系统实现
针对植物养殖行业的特殊性,我们实现了一个基于规则的智能推荐系统。该系统会考虑用户的购买历史、所在地区的气候条件以及植物的养护难度等因素,为用户推荐最适合的植物商品。
推荐算法的核心实现如下:
java复制public class PlantRecommendationEngine {
public List<PlantProduct> recommendPlants(User user, List<PlantProduct> candidatePlants) {
List<PlantProduct> recommended = new ArrayList<>();
// 根据用户所在地区气候筛选
candidatePlants = filterByClimate(user.getRegion(), candidatePlants);
// 根据用户养护经验筛选
candidatePlants = filterByMaintenanceLevel(user.getExperienceLevel(), candidatePlants);
// 根据用户偏好排序
candidatePlants.sort((p1, p2) -> {
double score1 = calculateScore(user, p1);
double score2 = calculateScore(user, p2);
return Double.compare(score2, score1);
});
// 返回前10个推荐结果
return candidatePlants.stream().limit(10).collect(Collectors.toList());
}
private double calculateScore(User user, PlantProduct plant) {
double score = 0;
// 偏好匹配加分
if (user.getPreferences().contains(plant.getCategory().getName())) {
score += 20;
}
// 价格区间匹配加分
if (plant.getPrice() >= user.getMinPricePreference() &&
plant.getPrice() <= user.getMaxPricePreference()) {
score += 15;
}
// 其他评分因素...
return score;
}
}
3.3 订单与支付系统
植物商品的订单处理有一些特殊要求,例如需要考虑配送时间对植物存活率的影响。我们实现了专门的订单处理逻辑:
java复制@Service
public class PlantOrderServiceImpl implements PlantOrderService {
@Autowired
private OrderMapper orderMapper;
@Autowired
private PlantProductService plantProductService;
@Autowired
private EmailService emailService;
@Override
@Transactional
public OrderResult createOrder(OrderRequest orderRequest) {
// 验证库存
for (OrderItem item : orderRequest.getItems()) {
if (!plantProductService.checkStock(item.getPlantId(), item.getQuantity())) {
throw new BusinessException("商品["+item.getPlantName()+"]库存不足");
}
}
// 创建订单
Order order = buildOrder(orderRequest);
orderMapper.insert(order);
// 扣减库存
for (OrderItem item : orderRequest.getItems()) {
plantProductService.reduceStock(item.getPlantId(), item.getQuantity());
orderMapper.insertItem(item);
}
// 发送养护指南
emailService.sendCareGuide(order.getUserId(), order.getId());
return buildOrderResult(order);
}
}
支付系统则集成了主流的支付平台接口,同时针对植物商品的高价值特性,增加了分期付款的支持。支付回调处理中,我们特别注意了事务的一致性问题:
java复制@Controller
@RequestMapping("/payment")
public class PaymentController {
@PostMapping("/callback")
@Transactional
public String handlePaymentCallback(PaymentCallbackRequest request) {
// 验证回调签名
if (!paymentService.verifySignature(request)) {
throw new SecurityException("非法回调请求");
}
// 处理支付结果
Order order = orderService.getOrderByNo(request.getOrderNo());
if (order == null) {
throw new BusinessException("订单不存在");
}
if (request.isSuccess()) {
orderService.paymentSuccess(order.getId(), request.getPaymentTime());
// 触发后续发货流程
shippingService.preparePlantShipping(order.getId());
} else {
orderService.paymentFailed(order.getId());
// 恢复库存
orderService.restoreStock(order.getId());
}
return "success";
}
}
4. 系统部署与优化
4.1 环境配置与部署
SSM植物养殖购买系统的部署需要考虑植物图片等静态资源的处理。我们推荐以下服务器配置方案:
- Web服务器:Tomcat 8.5+ 或 Jetty 9.4+
- 数据库:MySQL 5.7+,配置InnoDB引擎
- 文件存储:植物图片建议使用单独的文件服务器或云存储服务
- 缓存:Redis用于缓存热点植物数据和会话管理
部署时特别需要注意的配置项包括:
properties复制# 应用配置文件示例
spring.datasource.url=jdbc:mysql://localhost:3306/plant_shop?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=yourpassword
# 植物图片存储路径
plant.image.upload-path=/data/plant-images
plant.image.access-url=/plant-images/**
# 缓存配置
spring.cache.type=redis
spring.redis.host=localhost
spring.redis.port=6379
4.2 性能优化策略
针对植物养殖系统的特点,我们实施了多项性能优化措施:
- 植物数据缓存:将热门植物信息和分类数据缓存到Redis,减少数据库压力
java复制@Cacheable(value = "plants", key = "#id")
public PlantProduct getPlantById(Integer id) {
return plantProductMapper.selectById(id);
}
- 图片懒加载:植物列表页采用图片懒加载技术,提升页面加载速度
html复制<img class="lazy" data-src="/plant-images/${plant.imageUrl}" alt="${plant.name}">
- 数据库查询优化:为植物分类、生长条件等常用查询条件添加了合适的索引
sql复制ALTER TABLE plant_product ADD INDEX idx_category_condition (category_id, growth_condition);
- 异步处理:植物养护指南生成和发送采用异步处理,不影响主业务流程
java复制@Async
public void sendCareGuideAsync(Integer userId, Integer orderId) {
// 生成并发送养护指南
CareGuide guide = generateCareGuide(orderId);
emailService.sendEmail(userId, "您的植物养护指南", guide.getContent());
}
4.3 安全防护措施
植物养殖购买系统涉及在线交易,安全防护尤为重要。我们实施了以下安全措施:
- SQL注入防护:全程使用MyBatis的参数化查询,禁止拼接SQL
- XSS防护:对用户输入进行过滤,前端展示时进行转义
java复制public String escapeHtml(String input) {
if (input == null) return "";
return StringEscapeUtils.escapeHtml4(input);
}
- CSRF防护:Spring Security配置了CSRF防护
- 支付安全:支付接口采用HTTPS协议,敏感数据加密传输
- 权限控制:基于RBAC模型实现细粒度的权限管理
java复制@PreAuthorize("hasRole('ADMIN') or hasPermission(#plantId, 'plant:edit')")
public void updatePlant(Integer plantId, PlantProduct plant) {
plantProductMapper.update(plant);
}
5. 源码结构与二次开发指南
5.1 项目目录结构解析
SSM植物养殖购买系统的源码采用标准的Maven项目结构,但针对植物养殖业务做了一些特殊安排:
code复制plant-shop
├── src/main/java
│ ├── com/plantshop
│ │ ├── config # Spring配置类
│ │ ├── controller # 控制器层
│ │ ├── service # 业务逻辑层
│ │ │ ├── impl # 服务实现类
│ │ ├── dao # 数据访问层
│ │ ├── entity # 实体类
│ │ ├── dto # 数据传输对象
│ │ ├── util # 工具类
│ │ ├── exception # 异常处理
│ │ └── aspect # AOP切面
├── src/main/resources
│ ├── spring # Spring配置文件
│ ├── mybatis # MyBatis映射文件
│ ├── static # 静态资源
│ └── templates # 模板文件
└── src/test # 测试代码
特别值得注意的是,系统中为植物养护相关的业务逻辑单独建立了service包:
code复制plant-shop/src/main/java/com/plantshop/service
├── PlantCareService.java # 植物养护服务
├── PlantRecommendService.java # 植物推荐服务
├── PlantInventoryService.java # 植物库存服务
└── impl/ # 各服务的实现
5.2 二次开发扩展点
这套植物养殖购买系统设计时考虑了多个扩展点,方便进行二次开发:
- 植物生长追踪模块:可以通过扩展PlantCareService接口,实现更详细的植物生长状态追踪
java复制public interface PlantCareService {
void recordGrowthProgress(Integer plantId, GrowthRecord record);
List<GrowthRecord> getGrowthHistory(Integer plantId);
GrowthStatus getCurrentStatus(Integer plantId);
}
- 智能养护提醒:基于Quartz或Spring Scheduler实现定时养护提醒
java复制@Scheduled(cron = "0 0 9 * * ?") // 每天上午9点执行
public void sendDailyCareReminders() {
List<User> users = userService.getActiveUsers();
for (User user : users) {
List<PlantProduct> plants = getUsersPlants(user.getId());
careReminderService.sendReminders(user, plants);
}
}
- 植物社区功能:可以扩展用户互动模块,让用户分享植物养护经验
java复制@Controller
@RequestMapping("/community")
public class PlantCommunityController {
@PostMapping("/posts")
public String createPost(Post post) {
// 实现社区发帖逻辑
}
@GetMapping("/plants/{plantId}/advice")
public List<CareAdvice> getPlantCareAdvices(@PathVariable Integer plantId) {
// 获取特定植物的养护建议
}
}
- 批发采购模块:针对B端客户开发批发采购功能
java复制@Service
public class WholesaleServiceImpl implements WholesaleService {
public WholesaleQuote calculateQuote(WholesaleRequest request) {
// 实现批发报价逻辑
}
@Transactional
public WholesaleOrder createWholesaleOrder(WholesaleOrderRequest request) {
// 创建批发订单
}
}
5.3 测试与调试建议
对于这套植物养殖系统的测试,我们建议重点关注以下几个方面:
- 植物库存并发测试:模拟高并发下的库存扣减场景
java复制@Test
public void testConcurrentStockReduction() throws InterruptedException {
int threadCount = 50;
ExecutorService executor = Executors.newFixedThreadPool(threadCount);
CountDownLatch latch = new CountDownLatch(threadCount);
for (int i = 0; i < threadCount; i++) {
executor.execute(() -> {
try {
boolean success = plantProductService.reduceStock(1, 1);
assertTrue(success);
} finally {
latch.countDown();
}
});
}
latch.await();
executor.shutdown();
PlantProduct plant = plantProductService.getPlantById(1);
assertEquals(originalStock - threadCount, plant.getStock());
}
- 植物养护逻辑测试:验证不同生长条件下的养护建议是否正确
java复制@Test
public void testCareAdviceForDifferentConditions() {
PlantProduct plant1 = createPlant("Sunflower", "sunny", "easy");
CareAdvice advice1 = careService.generateAdvice(plant1);
assertTrue(advice1.getContent().contains("充足阳光"));
PlantProduct plant2 = createPlant("Fern", "shady", "medium");
CareAdvice advice2 = careService.generateAdvice(plant2);
assertTrue(advice2.getContent().contains("避免直射"));
}
- 订单全流程测试:从下单到支付再到发货的完整流程验证
java复制@Test
@Transactional
public void testCompleteOrderFlow() {
// 1. 用户下单
OrderRequest request = buildOrderRequest(testUser, testPlant, 2);
OrderResult result = orderService.createOrder(request);
// 2. 模拟支付回调
PaymentCallbackRequest callback = buildSuccessCallback(result.getOrderNo());
paymentController.handlePaymentCallback(callback);
// 3. 验证订单状态
Order order = orderService.getOrderByNo(result.getOrderNo());
assertEquals(OrderStatus.PAID, order.getStatus());
// 4. 验证库存
PlantProduct plant = plantProductService.getPlantById(testPlant.getId());
assertEquals(originalStock - 2, plant.getStock());
// 5. 验证养护指南是否发送
assertTrue(emailService.checkCareGuideSent(testUser.getId(), order.getId()));
}
6. 植物养殖行业特色功能实现
6.1 植物生长周期跟踪
针对植物商品的特殊性,我们实现了一套完整的生长周期跟踪系统。当用户购买植物后,系统会记录植物的生长阶段,并提供相应的养护建议:
java复制public class PlantGrowthTracker {
private static final Map<GrowthStage, CareAdvice> ADVICE_MAP = new EnumMap<>(GrowthStage.class);
static {
ADVICE_MAP.put(GrowthStage.SEEDLING, new CareAdvice("幼苗期", "保持土壤湿润,避免强光直射"));
ADVICE_MAP.put(GrowthStage.VEGETATIVE, new CareAdvice("生长期", "适量增加光照和肥料"));
ADVICE_MAP.put(GrowthStage.FLOWERING, new CareAdvice("开花期", "保持稳定环境,减少移动"));
ADVICE_MAP.put(GrowthStage.DORMANT, new CareAdvice("休眠期", "减少浇水,停止施肥"));
}
public GrowthRecord recordGrowth(Integer plantId, GrowthStage newStage) {
PlantGrowth growth = getCurrentGrowth(plantId);
GrowthRecord record = new GrowthRecord();
record.setPlantId(plantId);
record.setOldStage(growth.getCurrentStage());
record.setNewStage(newStage);
record.setRecordTime(new Date());
record.setAdvice(ADVICE_MAP.get(newStage));
growth.setCurrentStage(newStage);
updateGrowth(growth);
saveRecord(record);
return record;
}
}
6.2 养护知识库系统
为了帮助用户更好地养护植物,我们构建了一个养护知识库系统。该系统会根据植物种类自动关联相关的养护知识:
java复制@Service
public class PlantCareKnowledgeServiceImpl implements PlantCareKnowledgeService {
@Autowired
private CareArticleMapper articleMapper;
@Autowired
private PlantCategoryMapper categoryMapper;
@Override
public List<CareArticle> getRelatedArticles(Integer plantId) {
PlantProduct plant = plantProductMapper.selectById(plantId);
if (plant == null) {
return Collections.emptyList();
}
// 获取植物分类的所有父分类
List<Integer> categoryIds = getAllCategoryIds(plant.getCategoryId());
// 查询相关文章
return articleMapper.selectByCategories(categoryIds);
}
private List<Integer> getAllCategoryIds(Integer categoryId) {
List<Integer> ids = new ArrayList<>();
Category category = categoryMapper.selectById(categoryId);
while (category != null) {
ids.add(category.getId());
category = category.getParentId() != null ?
categoryMapper.selectById(category.getParentId()) : null;
}
return ids;
}
}
6.3 季节性植物推荐引擎
植物养殖具有很强的季节性特点,我们开发了一个季节性推荐引擎,会根据当前季节和即将到来的节日推荐适合的植物:
java复制public class SeasonalRecommender {
private static final Map<Month, List<String>> SEASONAL_PLANTS = new EnumMap<>(Month.class);
static {
SEASONAL_PLANTS.put(Month.JANUARY, Arrays.asList("仙客来", "蝴蝶兰"));
SEASONAL_PLANTS.put(Month.FEBRUARY, Arrays.asList("玫瑰", "郁金香"));
// ...其他月份配置
}
public List<PlantProduct> getSeasonalRecommendations() {
Month currentMonth = LocalDate.now().getMonth();
List<String> plantNames = SEASONAL_PLANTS.get(currentMonth);
// 特殊节日处理
if (isNearHoliday()) {
plantNames = adjustForHoliday(plantNames);
}
return plantProductMapper.selectByNames(plantNames);
}
private boolean isNearHoliday() {
// 判断是否临近重要节日
}
private List<String> adjustForHoliday(List<String> baseList) {
// 根据节日调整推荐列表
}
}
7. 系统特色与创新点
7.1 针对植物商品的特殊设计
SSM植物养殖购买系统在多个方面针对植物商品的特殊性进行了专门设计:
- 商品状态管理:除了常规的上架/下架状态外,还增加了"季节性供应"、"限量发售"等状态
java复制public enum PlantStatus {
AVAILABLE("可购买"),
SEASONAL("季节性供应"),
LIMITED("限量发售"),
PREORDER("预售"),
OUT_OF_STOCK("缺货"),
DISCONTINUED("停售");
private final String description;
// constructor and getter
}
- 配送时间计算:考虑植物特性,自动计算最佳配送时间
java复制public class PlantShippingCalculator {
public LocalDate calculateBestShippingDate(PlantProduct plant, String region) {
// 获取当前季节和天气数据
Season season = getCurrentSeason();
WeatherData weather = weatherService.getForecast(region);
// 计算最佳发货日期
if (plant.isColdSensitive() && weather.hasFrostWarning()) {
return weather.getNextWarmDay();
}
if (plant.isHeatSensitive() && weather.hasHeatWarning()) {
return weather.getNextCoolDay();
}
// 默认处理
return LocalDate.now().plusDays(1);
}
}
- 植物组合推荐:根据植物相生相克关系提供组合购买建议
java复制public List<PlantProduct> getCompanionPlants(Integer plantId) {
PlantProduct mainPlant = plantProductMapper.selectById(plantId);
List<CompanionRelation> relations = companionMapper.selectByMainPlant(mainPlant.getCategoryId());
List<Integer> companionIds = relations.stream()
.map(CompanionRelation::getCompanionCategoryId)
.collect(Collectors.toList());
return plantProductMapper.selectByCategories(companionIds).stream()
.filter(p -> !p.getId().equals(plantId))
.collect(Collectors.toList());
}
7.2 多维度植物数据管理
系统建立了完整的植物数据管理体系,包括:
- 植物属性扩展系统:采用动态字段设计,满足不同种类植物的特殊属性需求
java复制public class PlantAttributeExtension {
public void saveExtendedAttributes(Integer plantId, Map<String, Object> attributes) {
attributes.forEach((key, value) -> {
PlantAttribute attr = new PlantAttribute();
attr.setPlantId(plantId);
attr.setAttributeKey(key);
attr.setAttributeValue(value.toString());
attributeMapper.insert(attr);
});
}
public Map<String, String> getExtendedAttributes(Integer plantId) {
List<PlantAttribute> attrs = attributeMapper.selectByPlantId(plantId);
return attrs.stream()
.collect(Collectors.toMap(
PlantAttribute::getAttributeKey,
PlantAttribute::getAttributeValue));
}
}
- 植物养护日志系统:记录用户的养护操作和植物状态变化
java复制@Aspect
@Component
public class CareLogAspect {
@AfterReturning(
pointcut = "execution(* com.plantshop.service.PlantCareService.*(..)) && args(userId, plantId, ..)",
returning = "result")
public void logCareActivity(JoinPoint jp, Integer userId, Integer plantId, Object result) {
String methodName = jp.getSignature().getName();
CareActivity activity = new CareActivity();
activity.setUserId(userId);
activity.setPlantId(plantId);
activity.setActivityType(methodName);
activity.setActivityTime(new Date());
activity.setDetails(buildDetails(jp.getArgs(), result));
careActivityMapper.insert(activity);
}
}
7.3 智能化养护提醒系统
基于植物生长数据和用户养护习惯,系统实现了智能化的养护提醒:
- 个性化浇水提醒:根据植物种类、季节和环境调整提醒频率
java复制public class WateringReminderScheduler {
@Scheduled(cron = "0 0 8 * * ?") // 每天上午8点检查
public void generateDailyWateringReminders() {
List<UserPlant> userPlants = userPlantMapper.selectAllActive();
LocalDate today = LocalDate.now();
for (UserPlant userPlant : userPlants) {
PlantProduct plant = plantProductMapper.selectById(userPlant.getPlantId());
WateringFrequency frequency = calculateFrequency(plant, userPlant.getEnvironment());
if (shouldWaterToday(userPlant, frequency, today)) {
reminderService.sendWateringReminder(
userPlant.getUserId(),
userPlant.getPlantId(),
plant.getName());
userPlant.setLastWatered(today);
userPlantMapper.update(userPlant);
}
}
}
private boolean shouldWaterToday(UserPlant userPlant, WateringFrequency frequency, LocalDate today) {
// 根据植物需水特性和上次浇水时间判断
}
}
- 病虫害预警系统:基于地区病虫害数据和天气条件发送预警
java复制public class PestAlertService {
@Autowired
private WeatherDataService weatherService;
@Autowired
private PestDataService pestDataService;
public void checkAndSendAlerts(String region) {
List<PestAlert> alerts = new ArrayList<>();
// 获取可能发生的病虫害
List<PestForecast> forecasts = pestDataService.getForecasts(region);
WeatherCondition weather = weatherService.getCurrentWeather(region);
for (PestForecast forecast : forecasts) {
if (isConditionFavorable(forecast, weather)) {
alerts.add(createAlert(forecast, region));
}
}
if (!alerts.isEmpty()) {
sendAlertsToRegionUsers(region, alerts);
}
}
}
