1. 项目概述

这个基于Spring Boot的服装销售管理系统是我在计算机专业毕业设计中的实践成果。作为一个完整的电商平台,它涵盖了从用户注册、商品展示到订单管理的全流程功能。系统采用前后端分离架构,后端使用Spring Boot框架开发,前端基于Vue.js实现,数据库选用MySQL,并引入了协同过滤推荐算法来提升用户体验。

在实际开发过程中,我发现很多现有的电商系统要么功能过于简单,要么架构臃肿难以维护。因此,我决定设计一个既功能完善又易于扩展的系统架构。这个系统特别适合中小型服装电商企业使用,也适合作为计算机专业学生学习电商系统开发的参考案例。

2. 技术选型与架构设计

2.1 技术栈解析

2.1.1 Spring Boot框架优势

选择Spring Boot作为后端框架主要基于以下几个考虑:

  1. 快速开发:Spring Boot的自动配置和起步依赖大大减少了项目初始化的工作量
  2. 微服务友好:为将来可能的系统扩展预留了空间
  3. 丰富的生态系统:整合了Spring Security、Spring Data等组件

在实际开发中,我特别使用了Spring Boot的以下特性:

  • 使用Spring Data JPA简化数据库操作
  • 通过Spring Security实现权限控制
  • 利用Spring Cache提升系统性能
2.1.2 Vue.js前端框架

前端选择Vue.js主要因为:

  1. 渐进式框架:可以按需引入功能
  2. 组件化开发:提高代码复用率
  3. 响应式数据绑定:简化DOM操作

在实现过程中,我特别注重以下几点:

  • 使用Vue Router管理前端路由
  • 通过Vuex进行状态管理
  • 采用Element UI组件库加速开发
2.1.3 MySQL数据库

MySQL作为关系型数据库的选择理由:

  1. 成熟稳定:经过大量生产环境验证
  2. 性能优异:特别是对于读多写少的电商场景
  3. 社区支持:遇到问题容易找到解决方案

在数据库设计上,我特别注意了:

  • 合理设置索引提高查询效率
  • 使用InnoDB引擎保证事务完整性
  • 设计适当的冗余字段减少关联查询

2.2 系统架构设计

系统采用典型的分层架构:

┌───────────────────────────────────────┐
│               客户端层                │
│  (Web浏览器/移动端)                   │
└───────────────┬───────────────────────┘
                │ HTTP/HTTPS
┌───────────────▼───────────────────────┐
│               表现层                  │
│  (Vue.js前端应用)                     │
└───────────────┬───────────────────────┘
                │ REST API
┌───────────────▼───────────────────────┐
│              控制层                   │
│  (Spring Boot Controller)             │
└───────────────┬───────────────────────┘
                │ 服务调用
┌───────────────▼───────────────────────┐
│              服务层                   │
│  (业务逻辑处理)                       │
└───────────────┬───────────────────────┘
                │ 数据访问
┌───────────────▼───────────────────────┐
│             数据访问层                │
│  (Spring Data JPA/MyBatis)            │
└───────────────┬───────────────────────┘
                │ JDBC
┌───────────────▼───────────────────────┐
│              数据库层                 │
│  (MySQL)                              │
└───────────────────────────────────────┘

这种分层架构的优势在于:

  1. 职责分离:各层专注自己的功能
  2. 易于维护:修改某层不会影响其他层
  3. 可扩展性强:可以单独扩展某一层

3. 核心功能实现

3.1 用户模块实现

3.1.1 用户注册与登录

用户注册流程的关键代码实现:

@PostMapping("/register")
public Result register(@RequestBody User user) {
    // 检查用户名是否已存在
    if(userService.findByUsername(user.getUsername()) != null){
        return Result.error("用户名已存在");
    }
    
    // 密码加密
    user.setPassword(passwordEncoder.encode(user.getPassword()));
    
    // 设置默认角色
    user.setRole(Role.USER);
    
    // 保存用户
    userService.save(user);
    
    return Result.success("注册成功");
}

登录功能采用JWT认证方式:

@PostMapping("/login")
public Result login(@RequestBody LoginDto loginDto) {
    // 验证用户
    User user = userService.findByUsername(loginDto.getUsername());
    if(user == null || !passwordEncoder.matches(loginDto.getPassword(), user.getPassword())){
        return Result.error("用户名或密码错误");
    }
    
    // 生成JWT token
    String token = JwtUtil.generateToken(user);
    
    // 返回token和用户信息
    Map<String, Object> data = new HashMap<>();
    data.put("token", token);
    data.put("user", user);
    
    return Result.success(data);
}
3.1.2 权限控制实现

使用Spring Security实现基于角色的权限控制:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeRequests()
                .antMatchers("/api/user/**").hasAnyRole("USER", "ADMIN")
                .antMatchers("/api/admin/**").hasRole("ADMIN")
                .antMatchers("/api/**").authenticated()
                .anyRequest().permitAll()
            .and()
            .addFilter(new JwtAuthenticationFilter(authenticationManager()))
            .addFilter(new JwtAuthorizationFilter(authenticationManager()))
            .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}

3.2 商品模块实现

3.2.1 商品CRUD操作

商品实体类设计:

@Entity
@Table(name = "product")
@Data
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    private String name;
    private String description;
    private BigDecimal price;
    private Integer stock;
    
    @Enumerated(EnumType.STRING)
    private ProductCategory category;
    
    private String imageUrl;
    
    @ManyToOne
    @JoinColumn(name = "merchant_id")
    private User merchant;
    
    @OneToMany(mappedBy = "product")
    private List<OrderItem> orderItems;
}

商品服务层实现:

@Service
public class ProductService {
    
    @Autowired
    private ProductRepository productRepository;
    
    public Page<Product> findAll(Pageable pageable) {
        return productRepository.findAll(pageable);
    }
    
    public Product findById(Long id) {
        return productRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("Product not found"));
    }
    
    public Product save(Product product) {
        return productRepository.save(product);
    }
    
    public void deleteById(Long id) {
        productRepository.deleteById(id);
    }
    
    public Page<Product> search(String keyword, Pageable pageable) {
        return productRepository.findByNameContainingOrDescriptionContaining(keyword, keyword, pageable);
    }
}
3.2.2 商品搜索与筛选

实现商品搜索的几种方式:

  1. 简单搜索(基于JPA):
public interface ProductRepository extends JpaRepository<Product, Long> {
    Page<Product> findByNameContainingOrDescriptionContaining(String name, String description, Pageable pageable);
}
  1. 高级筛选:
public Page<Product> filterProducts(ProductFilter filter, Pageable pageable) {
    Specification<Product> spec = Specification.where(null);
    
    if(filter.getName() != null) {
        spec = spec.and((root, query, cb) -> 
            cb.like(root.get("name"), "%" + filter.getName() + "%"));
    }
    
    if(filter.getMinPrice() != null) {
        spec = spec.and((root, query, cb) -> 
            cb.greaterThanOrEqualTo(root.get("price"), filter.getMinPrice()));
    }
    
    if(filter.getMaxPrice() != null) {
        spec = spec.and((root, query, cb) -> 
            cb.lessThanOrEqualTo(root.get("price"), filter.getMaxPrice()));
    }
    
    if(filter.getCategory() != null) {
        spec = spec.and((root, query, cb) -> 
            cb.equal(root.get("category"), filter.getCategory()));
    }
    
    return productRepository.findAll(spec, pageable);
}

3.3 订单模块实现

3.3.1 购物车功能

购物车数据结构设计:

@Entity
@Table(name = "cart")
@Data
public class Cart {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @OneToOne
    @JoinColumn(name = "user_id")
    private User user;
    
    @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<CartItem> items = new ArrayList<>();
    
    public void addItem(Product product, int quantity) {
        Optional<CartItem> existingItem = items.stream()
            .filter(item -> item.getProduct().equals(product))
            .findFirst();
            
        if(existingItem.isPresent()) {
            existingItem.get().setQuantity(existingItem.get().getQuantity() + quantity);
        } else {
            CartItem newItem = new CartItem();
            newItem.setCart(this);
            newItem.setProduct(product);
            newItem.setQuantity(quantity);
            items.add(newItem);
        }
    }
    
    public void removeItem(Product product) {
        items.removeIf(item -> item.getProduct().equals(product));
    }
    
    public BigDecimal getTotalPrice() {
        return items.stream()
            .map(item -> item.getProduct().getPrice().multiply(BigDecimal.valueOf(item.getQuantity())))
            .reduce(BigDecimal.ZERO, BigDecimal::add);
    }
}
3.3.2 订单创建与支付

订单创建流程:

@Service
@Transactional
public class OrderService {
    
    @Autowired
    private CartRepository cartRepository;
    
    @Autowired
    private OrderRepository orderRepository;
    
    @Autowired
    private ProductService productService;
    
    public Order createOrder(Long userId, String shippingAddress) {
        // 获取用户购物车
        Cart cart = cartRepository.findByUserId(userId)
                .orElseThrow(() -> new ResourceNotFoundException("Cart not found"));
        
        // 检查库存
        for(CartItem item : cart.getItems()) {
            Product product = item.getProduct();
            if(product.getStock() < item.getQuantity()) {
                throw new InsufficientStockException("Insufficient stock for product: " + product.getName());
            }
        }
        
        // 扣减库存
        for(CartItem item : cart.getItems()) {
            Product product = item.getProduct();
            product.setStock(product.getStock() - item.getQuantity());
            productService.save(product);
        }
        
        // 创建订单
        Order order = new Order();
        order.setUser(cart.getUser());
        order.setOrderDate(LocalDateTime.now());
        order.setStatus(OrderStatus.PENDING);
        order.setShippingAddress(shippingAddress);
        order.setTotalAmount(cart.getTotalPrice());
        
        // 添加订单项
        List<OrderItem> orderItems = cart.getItems().stream()
            .map(cartItem -> {
                OrderItem orderItem = new OrderItem();
                orderItem.setOrder(order);
                orderItem.setProduct(cartItem.getProduct());
                orderItem.setQuantity(cartItem.getQuantity());
                orderItem.setPrice(cartItem.getProduct().getPrice());
                return orderItem;
            })
            .collect(Collectors.toList());
        
        order.setItems(orderItems);
        
        // 保存订单
        Order savedOrder = orderRepository.save(order);
        
        // 清空购物车
        cart.getItems().clear();
        cartRepository.save(cart);
        
        return savedOrder;
    }
}

3.4 推荐系统实现

3.4.1 协同过滤算法

基于用户的协同过滤实现:

@Service
public class RecommendationService {
    
    @Autowired
    private UserBehaviorRepository behaviorRepository;
    
    @Autowired
    private ProductRepository productRepository;
    
    public List<Product> recommendForUser(Long userId, int limit) {
        // 获取目标用户的行为数据
        List<UserBehavior> targetBehaviors = behaviorRepository.findByUserId(userId);
        
        if(targetBehaviors.isEmpty()) {
            // 如果没有行为数据,返回热门商品
            return productRepository.findTopByOrderBySalesDesc(PageRequest.of(0, limit));
        }
        
        // 获取所有用户的行为数据
        List<UserBehavior> allBehaviors = behaviorRepository.findAll();
        
        // 计算用户相似度
        Map<Long, Double> userSimilarities = new HashMap<>();
        for(UserBehavior behavior : allBehaviors) {
            if(behavior.getUserId().equals(userId)) continue;
            
            double similarity = calculateUserSimilarity(userId, behavior.getUserId(), targetBehaviors);
            userSimilarities.merge(behavior.getUserId(), similarity, Double::sum);
        }
        
        // 找出最相似的K个用户
        List<Long> similarUsers = userSimilarities.entrySet().stream()
            .sorted(Map.Entry.<Long, Double>comparingByValue().reversed())
            .limit(5)
            .map(Map.Entry::getKey)
            .collect(Collectors.toList());
        
        // 获取这些用户喜欢的商品
        Map<Long, Double> productScores = new HashMap<>();
        for(Long similarUserId : similarUsers) {
            List<UserBehavior> similarUserBehaviors = behaviorRepository.findByUserId(similarUserId);
            
            for(UserBehavior behavior : similarUserBehaviors) {
                if(targetBehaviors.stream().noneMatch(b -> b.getProductId().equals(behavior.getProductId()))) {
                    double score = userSimilarities.get(similarUserId) * behavior.getScore();
                    productScores.merge(behavior.getProductId(), score, Double::sum);
                }
            }
        }
        
        // 获取评分最高的商品
        return productScores.entrySet().stream()
            .sorted(Map.Entry.<Long, Double>comparingByValue().reversed())
            .limit(limit)
            .map(entry -> productRepository.findById(entry.getKey()).orElse(null))
            .filter(Objects::nonNull)
            .collect(Collectors.toList());
    }
    
    private double calculateUserSimilarity(Long userId1, Long userId2, List<UserBehavior> user1Behaviors) {
        List<UserBehavior> user2Behaviors = behaviorRepository.findByUserId(userId2);
        
        // 计算余弦相似度
        double dotProduct = 0.0;
        double norm1 = 0.0;
        double norm2 = 0.0;
        
        // 这里简化处理,实际应用中可能需要更复杂的相似度计算
        for(UserBehavior b1 : user1Behaviors) {
            for(UserBehavior b2 : user2Behaviors) {
                if(b1.getProductId().equals(b2.getProductId())) {
                    dotProduct += b1.getScore() * b2.getScore();
                }
            }
            norm1 += b1.getScore() * b1.getScore();
        }
        
        for(UserBehavior b2 : user2Behaviors) {
            norm2 += b2.getScore() * b2.getScore();
        }
        
        return dotProduct / (Math.sqrt(norm1) * Math.sqrt(norm2));
    }
}
3.4.2 推荐结果缓存

为了提高推荐系统的响应速度,可以使用Redis缓存推荐结果:

@Service
public class CachedRecommendationService {
    
    @Autowired
    private RecommendationService recommendationService;
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    private static final String RECOMMENDATION_KEY_PREFIX = "recommendations:user:";
    private static final long CACHE_EXPIRE_HOURS = 24;
    
    @Cacheable(value = "userRecommendations", key = "#userId")
    public List<Product> recommendForUser(Long userId, int limit) {
        String cacheKey = RECOMMENDATION_KEY_PREFIX + userId;
        
        // 尝试从缓存获取
        List<Product> cached = (List<Product>) redisTemplate.opsForValue().get(cacheKey);
        if(cached != null) {
            return cached.stream().limit(limit).collect(Collectors.toList());
        }
        
        // 缓存中没有,调用实际推荐服务
        List<Product> recommendations = recommendationService.recommendForUser(userId, limit);
        
        // 存入缓存
        redisTemplate.opsForValue().set(cacheKey, recommendations, CACHE_EXPIRE_HOURS, TimeUnit.HOURS);
        
        return recommendations;
    }
    
    public void clearUserRecommendations(Long userId) {
        String cacheKey = RECOMMENDATION_KEY_PREFIX + userId;
        redisTemplate.delete(cacheKey);
    }
}

4. 系统部署与优化

4.1 数据库优化

4.1.1 索引优化

为常用查询字段添加索引:

-- 用户表索引
CREATE INDEX idx_user_username ON user(username);
CREATE INDEX idx_user_email ON user(email);

-- 商品表索引
CREATE INDEX idx_product_name ON product(name);
CREATE INDEX idx_product_category ON product(category);
CREATE INDEX idx_product_price ON product(price);

-- 订单表索引
CREATE INDEX idx_order_user_id ON `order`(user_id);
CREATE INDEX idx_order_status ON `order`(status);
CREATE INDEX idx_order_date ON `order`(order_date);
4.1.2 查询优化

使用EXPLAIN分析慢查询:

EXPLAIN SELECT * FROM product 
WHERE category = 'MEN' 
AND price BETWEEN 100 AND 500 
ORDER BY create_time DESC 
LIMIT 20;

根据分析结果调整查询方式或表结构。

4.2 应用性能优化

4.2.1 缓存策略
  1. 使用Spring Cache抽象层:
@Configuration
@EnableCaching
public class CacheConfig {
    
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofHours(1))
            .disableCachingNullValues()
            .serializeValuesWith(RedisSerializationContext.SerializationPair
                .fromSerializer(new GenericJackson2JsonRedisSerializer()));
        
        return RedisCacheManager.builder(factory)
            .cacheDefaults(config)
            .transactionAware()
            .build();
    }
}
  1. 在服务方法上使用缓存注解:
@Service
public class ProductServiceImpl implements ProductService {
    
    @Cacheable(value = "products", key = "#id")
    public Product findById(Long id) {
        // 数据库查询
    }
    
    @CacheEvict(value = "products", key = "#product.id")
    public Product update(Product product) {
        // 更新操作
    }
}
4.2.2 异步处理

对于非实时要求的操作,可以使用异步处理:

@Service
public class OrderService {
    
    @Async
    public void sendOrderConfirmationEmail(Order order) {
        // 发送邮件
    }
    
    @Async
    public void updateInventoryAsync(List<OrderItem> items) {
        // 异步更新库存
    }
}

4.3 安全防护

4.3.1 防止SQL注入

使用JPA或MyBatis等ORM框架可以自动防止SQL注入。如果必须使用原生SQL,应使用参数化查询:

@Query(value = "SELECT * FROM product WHERE name LIKE %:keyword%", nativeQuery = true)
List<Product> searchProducts(@Param("keyword") String keyword);
4.3.2 XSS防护

前端使用Vue.js的文本插值会自动转义HTML:

<div>{{ userInput }}</div>

后端也可以对用户输入进行过滤:

public String sanitize(String input) {
    return HtmlUtils.htmlEscape(input);
}
4.3.3 CSRF防护

虽然REST API通常不使用CSRF防护,但如果需要可以启用:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}

5. 开发经验与问题解决

5.1 开发中的典型问题

5.1.1 跨域问题解决

在前后端分离架构中,跨域是常见问题。解决方案:

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
            .allowedOrigins("http://localhost:8080")
            .allowedMethods("GET", "POST", "PUT", "DELETE")
            .allowedHeaders("*")
            .allowCredentials(true)
            .maxAge(3600);
    }
}
5.1.2 事务管理问题

在复杂业务逻辑中,事务管理容易出现问题。解决方案:

@Service
public class OrderService {
    
    @Transactional(rollbackFor = Exception.class)
    public Order createOrder(OrderDto orderDto) {
        // 复杂的业务逻辑
    }
}

注意:默认情况下,Spring只对运行时异常进行回滚,检查异常不会触发回滚。

5.2 性能调优经验

5.2.1 N+1查询问题

在使用JPA时容易出现N+1查询问题。解决方案:

  1. 使用JOIN FETCH:
@Query("SELECT o FROM Order o JOIN FETCH o.items WHERE o.user.id = :userId")
List<Order> findOrdersWithItemsByUser(@Param("userId") Long userId);
  1. 使用@EntityGraph:
@EntityGraph(attributePaths = {"items"})
List<Order> findByUserId(Long userId);
5.2.2 批量操作优化

对于批量插入/更新操作,应进行优化:

@Transactional
public void batchInsertProducts(List<Product> products) {
    for(int i = 0; i < products.size(); i++) {
        entityManager.persist(products.get(i));
        if(i % 50 == 0) {
            entityManager.flush();
            entityManager.clear();
        }
    }
}

5.3 测试经验分享

5.3.1 单元测试实践

使用JUnit和Mockito编写单元测试:

@ExtendWith(MockitoExtension.class)
class ProductServiceTest {
    
    @Mock
    private ProductRepository productRepository;
    
    @InjectMocks
    private ProductServiceImpl productService;
    
    @Test
    void shouldReturnProductWhenValidId() {
        // 准备测试数据
        Product mockProduct = new Product();
        mockProduct.setId(1L);
        mockProduct.setName("Test Product");
        
        // 定义mock行为
        when(productRepository.findById(1L)).thenReturn(Optional.of(mockProduct));
        
        // 调用测试方法
        Product result = productService.findById(1L);
        
        // 验证结果
        assertNotNull(result);
        assertEquals("Test Product", result.getName());
        
        // 验证mock交互
        verify(productRepository).findById(1L);
    }
}
5.3.2 集成测试实践

使用Spring Boot Test进行集成测试:

@SpringBootTest
@AutoConfigureMockMvc
class OrderControllerIntegrationTest {
    
    @Autowired
    private MockMvc mockMvc;
    
    @Autowired
    private ObjectMapper objectMapper;
    
    @Test
    @WithMockUser
    void shouldCreateOrder() throws Exception {
        OrderDto orderDto = new OrderDto();
        // 设置orderDto属性
        
        mockMvc.perform(post("/api/orders")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(orderDto)))
            .andExpect(status().isCreated())
            .andExpect(jsonPath("$.id").exists());
    }
}

6. 系统扩展与未来改进

6.1 功能扩展方向

6.1.1 社交化功能
  1. 用户评价与晒单
  2. 商品收藏与分享
  3. 用户关注与粉丝系统
6.1.2 营销功能
  1. 优惠券系统
  2. 积分奖励
  3. 拼团/秒杀活动

6.2 技术改进方向

6.2.1 微服务化改造

将单体应用拆分为微服务:

  1. 用户服务
  2. 商品服务
  3. 订单服务
  4. 推荐服务

使用Spring Cloud实现服务治理。

6.2.2 推荐算法优化
  1. 引入深度学习模型
  2. 增加多维度特征
  3. 实现实时推荐

6.3 运维改进方向

6.3.1 监控系统搭建
  1. 使用Prometheus收集指标
  2. 使用Grafana展示监控数据
  3. 设置告警规则
6.3.2 日志系统改进
  1. 使用ELK栈收集分析日志
  2. 实现分布式追踪
  3. 设置日志归档策略

在开发这个系统的过程中,我深刻体会到良好的系统架构设计对项目成功的重要性。特别是在电商系统中,性能、安全性和可扩展性都需要仔细考虑。通过这个项目,我不仅巩固了Spring Boot和Vue.js等技术栈的应用能力,还学到了很多关于系统设计和优化的实践经验。

Logo

电商企业物流数字化转型必备!快递鸟 API 接口,72 小时快速完成物流系统集成。全流程实战1V1指导,营造开放的API技术生态圈。

更多推荐