Spring Boot 服裝推薦系統實例
以下是基于Spring Boot實現的服裝推薦系統的30個實例代碼示例,涵蓋核心功能和實現方法。
用戶注冊與登錄功能
@RestController
@RequestMapping("/api/auth")
public class AuthController {@Autowiredprivate UserService userService;@PostMapping("/register")public ResponseEntity<?> registerUser(@RequestBody UserDto userDto) {userService.registerUser(userDto);return ResponseEntity.ok("User registered successfully");}@PostMapping("/login")public ResponseEntity<?> authenticateUser(@RequestBody LoginDto loginDto) {Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginDto.getUsername(), loginDto.getPassword()));SecurityContextHolder.getContext().setAuthentication(authentication);String jwt = jwtUtils.generateJwtToken(authentication);return ResponseEntity.ok(new JwtResponse(jwt));}
}
服裝數據模型
@Entity
@Table(name = "clothing_items")
public class ClothingItem {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;private String name;private String category;private String color;private String size;private String material;private String brand;private double price;private String imageUrl;@ManyToMany(mappedBy = "clothingItems")private Set<User> users = new HashSet<>();
}
推薦算法實現
@Service
public class RecommendationService {public List<ClothingItem> recommendItemsBasedOnUserPreferences(User user) {List<ClothingItem> allItems = clothingItemRepository.findAll();Map<ClothingItem, Double> itemScores = new HashMap<>();for (ClothingItem item : allItems) {double score = calculateMatchScore(user.getPreferences(), item);itemScores.put(item, score);}return itemScores.entrySet().stream().sorted(Map.Entry.<ClothingItem, Double>comparingByValue().reversed()).limit(10).map(Map.Entry::getKey).collect(Collectors.toList());}private double calculateMatchScore(UserPreferences preferences, ClothingItem item) {double score = 0;if (preferences.getPreferredColors().contains(item.getColor())) score += 0.3;if (preferences.getPreferredCategories().contains(item.getCategory())) score += 0.4;if (preferences.getPreferredPriceRange().contains(item.getPrice())) score += 0.3;return score;}
}
用戶偏好設置
@RestController
@RequestMapping("/api/preferences")
public class PreferenceController {@Autowiredprivate PreferenceService preferenceService;@PostMappingpublic ResponseEntity<?> setUserPreferences(@RequestBody UserPreferencesDto preferencesDto,@AuthenticationPrincipal UserDetails userDetails) {preferenceService.saveUserPreferences(userDetails.getUsername(), preferencesDto);return ResponseEntity.ok("Preferences saved successfully");}@GetMappingpublic ResponseEntity<?> getUserPreferences(@AuthenticationPrincipal UserDetails userDetails) {UserPreferences preferences = preferenceService.getUserPreferences(userDetails.getUsername());return ResponseEntity.ok(preferences);}
}
天氣數據集成
@Service
public class WeatherService {@Value("${weather.api.key}")private String apiKey;public WeatherData getCurrentWeather(String location) {String url = String.format("https://api.weatherapi.com/v1/current.json?key=%s&q=%s", apiKey, location);RestTemplate restTemplate = new RestTemplate();ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);return parseWeatherData(response.getBody());}private WeatherData parseWeatherData(String json) {// JSON parsing logic}
}
基于天氣的推薦
@Service
public class WeatherBasedRecommendationService {@Autowiredprivate WeatherService weatherService;@Autowiredprivate ClothingItemRepository clothingItemRepository;public List<ClothingItem> getWeatherBasedRecommendations(String location) {WeatherData weather = weatherService.getCurrentWeather(location);return clothingItemRepository.findByTemperatureRange(calculateTemperatureRange(weather.getTemperature()));}private String calculateTemperatureRange(double temp) {if (temp < 10) return "WINTER";else if (temp < 20) return "COOL";else return "SUMMER";}
}
用戶行為跟蹤
@Entity
@Table(name = "user_activities")
public class UserActivity {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;@ManyToOneprivate User user;private Long clothingItemId;private ActivityType activityType; // VIEW, LIKE, PURCHASE, etc.private LocalDateTime timestamp;
}
協同過濾推薦
@Service
public class CollaborativeFilteringService {public List<ClothingItem> getCollaborativeRecommendations(Long userId) {List<UserActivity> activities = userActivityRepository.findByUserId(userId);Set<Long> viewedItems = activities.stream().map(UserActivity::getClothingItemId).collect(Collectors.toSet());Map<Long, Double> itemSimilarities = new HashMap<>();for (Long itemId : viewedItems) {ClothingItem item = clothingItemRepository.findById(itemId).orElseThrow();for (ClothingItem other : clothingItemRepository.findAll()) {if (!viewedItems.contains(other.getId())) {double similarity = calculateItemSimilarity(item, other);itemSimilarities.merge(other.getId(), similarity, Double::sum);}}}return itemSimilarities.entrySet().stream().sorted(Map.Entry.<Long, Double>comparingByValue().reversed()).limit(10).map(entry -> clothingItemRepository.findById(entry.getKey()).orElseThrow()).collect(Collectors.toList());}
}
內容過濾推薦
@Service
public class ContentBasedFilteringService {public List<ClothingItem> getContentBasedRecommendations(User user) {List<UserActivity> likedActivities = userActivityRepository.findByUserIdAndActivityType(user.getId(), ActivityType.LIKE);if (likedActivities.isEmpty()) {return Collections.emptyList();}Map<String, Integer> categoryCounts = new HashMap<>();Map<String, Integer> colorCounts = new HashMap<>();Map<String, Integer> materialCounts = new HashMap<>();for (UserActivity activity : likedActivities) {ClothingItem item = clothingItemRepository.findById(activity.getClothingItemId()).orElseThrow();categoryCounts.merge(item.getCategory(), 1, Integer::sum);colorCounts.merge(item.getColor(), 1, Integer::sum);materialCounts.merge(item.getMaterial(), 1, Integer::sum);}String topCategory = Collections.max(categoryCounts.entrySet(), Map.Entry.comparingByValue()).getKey();String topColor = Collections.max(colorCounts.entrySet(), Map.Entry.comparingByValue()).getKey();String topMaterial = Collections.max(materialCounts.entrySet(), Map.Entry.comparingByValue()).getKey();return clothingItemRepository.findByCategoryOrColorOrMaterial(topCategory, topColor, topMaterial);}
}
混合推薦系統
@Service
public class HybridRecommendationService {@Autowiredprivate ContentBasedFilteringService contentBasedService;@Autowiredprivate CollaborativeFilteringService collaborativeService;@Autowiredprivate WeatherBasedRecommendationService weatherBasedService;public List<ClothingItem> getHybridRecommendations(User user, String location) {List<ClothingItem> contentBased = contentBasedService.getContentBasedRecommendations(user);List<ClothingItem> collaborative = collaborativeService.getCollaborativeRecommendations(user.getId());List<ClothingItem> weatherBased = weatherBasedService.getWeatherBasedRecommendations(location);Set<ClothingItem> recommendations = new HashSet<>();recommendations.addAll(contentBased);recommendations.addAll(collaborative);recommendations.addAll(weatherBased);return new ArrayList<>(recommendations).stream().limit(15).collect(Collectors.toList());}
}
服裝分類API
@RestController
@RequestMapping("/api/clothing")
public class ClothingController {@GetMapping("/categories")public ResponseEntity<?> getAllCategories() {List<String> categories = clothingItemRepository.findDistinctCategories();return ResponseEntity.ok(categories);}@GetMapping("/by-category/{category}")public ResponseEntity<?> getItemsByCategory(@PathVariable String category) {List<ClothingItem> items = clothingItemRepository.findByCategory(category);return ResponseEntity.ok(items);}
}
用戶收藏功能
@RestController
@RequestMapping("/api/favorites")
public class FavoriteController {@PostMapping("/add")pu