发表于: 2025-05-22 20:51:47

0 48


今天完成的任务:继续任务点:

  • 17.用Spring messageSource 配置错误信息,在接口处做校验,根据错误的类型返回对应的错误信息


首先配置了一下资源内文件:

@Configuration

public class MessageSourceConfig {

    @Bean

    public MessageSource messageSource() {

        ResourceBundleMessageSource source = new ResourceBundleMessageSource();

        source.setBasenames("i18n/messages"); // 资源文件路径(如src/main/resources/i18n/messages.properties)

        source.setDefaultEncoding("UTF-8");

        return source;

    }

}


修改了控制器层:

@RestController

@RequestMapping("/api/pengsql")

public class PengsqlController {

    private final PengsqlSerivce pengsqlService;

    private final MessageSource messageSource; // 新增注入

    @Autowired

    public PengsqlController(PengsqlSerivce pengsqlService, MessageSource messageSource) {

        this.pengsqlService = pengsqlService;

        this.messageSource = messageSource; // 注入MessageSource

    }

 

    @PostMapping

    public ResponseEntity<Map<String, Object>> create(@RequestBody Pengsql pengsql, Locale locale) {

        Map<String, Object> response = new LinkedHashMap<>();

        response.put("code", 200);

        // 使用MessageSource获取国际化消息

        response.put("message", messageSource.getMessage("operation.success", null, locale));

        return ResponseEntity.ok(response);

    }

}

明天的任务:继续任务点,下载Nginx。


返回列表 返回列表
评论

    分享到