Spring Boot 服装推荐系统实例
以下是基于Spring Boot实现的服装推荐系统的30个实例代码示例,涵盖核心功能和实现方法。
用户注册与登录功能
@RestController
@RequestMapping("/api/auth")
public class AuthController {
@Autowired
private 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 {
@Autowired
private PreferenceService preferenceService;
@PostMapping
public ResponseEntity<?> setUserPreferences(@RequestBody UserPreferencesDto preferencesDto,
@AuthenticationPrincipal UserDetails userDetails) {
preferenceService.saveUserPreferences(userDetails.getUsername(), preferencesDto);
return ResponseEntity.ok("Preferences saved successfully");
}
@GetMapping
public 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 {
@Autowired
private WeatherService weatherService;
@Autowired
private 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;
@ManyToOne
private 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 {
@Autowired
private ContentBasedFilteringService contentBasedService;
@Autowired
private CollaborativeFilteringService collaborativeService;
@Autowired
private 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