Spring Boot 自定义属性 以及 乱码问题

本文介绍如何在Spring Boot中使用自定义属性,包括如何在application.properties中配置自定义属性并在代码中通过@Value注解获取这些属性。此外,还介绍了如何使用随机数作为配置项,并通过@ConfigurationProperties将多个配置绑定到一个对象的bean中。最后,解决了中文配置项可能出现的乱码问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自定义属性

application.properties提供自定义属性的支持,这样我们就可以把一些常量配置在这里:

#自定义属性
com.waiting.custom.one=自定义属性ONE com.waiting.custom.two=自定义属性TWO com.waiting.custom.three=3
  • 1
  • 2
  • 3
  • 4

然后直接在要使用的地方通过注解@Value(value="${config.name}")取出:

@RestController
public class HelloController { public final static Logger logger = LoggerFactory.getLogger(HelloController.class); @Value("${com.waiting.custom.one}") private String stringOne; @Value("${com.waiting.custom.two}") private String stringTwo; @Value("${com.waiting.custom.three}") private Integer integerThree; @RequestMapping(value = "/",name = "Hello") public String testHello(){ logger.info("logback-ok"); return "Hello Spring-boot!"+stringOne+stringTwo+integerThree; } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

这里写图片描述

使用随机数及自定义配置类

有时候我们需要我们的参数不是一个固定值,而是一个随机数(比如密钥)。Spring Boot的属性配置文件中可以通过${random}来产生int值、long值或者String字符串,来支持属性的随机值。

#随机字符串
com.waiting.random.str=${random.value} #随机int com.waiting.random.number=${random.int} #随机long com.waiting.random.bigNumber=${random.long} #10以内的随机数 com.waiting.random.test1=${random.int(10)} #10-20的随机数 com.waiting.random.test2=${random.int[10,20]}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

在这边配置中我们发现有一个特点,所有配置都是以"com.waiting.random"开头的,而且有时候属性太多了,一个个绑定到属性字段上太累,官方提倡绑定一个对象的bean,这里我们建一个RandomProperties .java类,顶部需要使用注解@ConfigurationProperties(prefix = "com.waiting.random")来进行声明:

//@Configuration
//@Component
@ConfigurationProperties(prefix = "com.waiting.random")
public class RandomProperties { private String str; private Integer number; private Long bigNumber; private Integer test1; private Integer test2; // getter/setter方法省略 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

此时配置完还需要在spring Boot入口类加上@EnableConfigurationProperties并指明要加载哪个bean,如果不写RandomProperties.class,在bean类那边添加@Configuration或者@Component

@SpringBootApplication
@EnableConfigurationProperties({RandomProperties.class})
public class SpringbootdemoApplication { public static void main(String[] args) { SpringApplication.run(SpringbootdemoApplication.class, args); } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

把所有的自定义配置都放在application.properties里面会显得臃肿,这时候我们可以另外定义一个配置文件,这里我明取名为random.properties,路径放在src/main/resources/waiting下面。
这里只需要在之前的bean上添加@PropertySource("classpath:waiting/random.properties")@Configuration这个注解就可以了。
注意:不能再采取之前的@EnableConfigurationProperties({RandomProperties.class})这个方法。
最后controller层或service获取的时候用@Autowired注解就可以获取。

    @Autowired
    private  RandomProperties randomProperties;

    @Value("${com.waiting.custom.one}") private String stringOne; @Value("${com.waiting.custom.two}") private String stringTwo; @Value("${com.waiting.custom.three}") private Integer integerThree; @RequestMapping(value = "/",name = "Hello") public String testHello(){ logger.info("logback-ok"); return "Hello Spring-boot!"+stringOne+stringTwo+integerThree+"\r"+randomProperties; } 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

这里写图片描述

中文乱码问题

当在.properties的配置文件中有中文时,读取出来的是乱码。需要进行如下操作:

1、添加配置

#设置spring-boot 编码格式
banner.charset=UTF-8
server.tomcat.uri-encoding=UTF-8 spring.http.encoding.charset=UTF-8 spring.http.encoding.enabled=true spring.http.encoding.force=true spring.messages.encoding=UTF-8
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

2、设置文件类型

application.properites的文件类型修改为UTF-8的编码类型。
通过以上方法测试获取出来的值还是乱码。

解决办法

2.1、IDEA

设置 File Encodings的Transparent native-to-ascii conversion为true,具体步骤如下:
依次点击
File -> Settings -> Editor -> File Encodings
将Properties Files (*.properties)下的Default encoding for properties files设置为UTF-8,将Transparent native-to-ascii conversion前的勾选上。

2.2、eclipse

在eclipse中安装properties插件PropertiesEditor及设置(附图),ASCII码转换成中文
推荐使用里面的离线安装。安装完成PropertiesEditor 插件后,使用该编辑器重新编辑属性文件中的中文,然后重新运行程序,发现读取的中文配置文件不是乱码了。

转载于:https://www.cnblogs.com/hfultrastrong/p/8779924.html

<think>好的,用户之前已经问过如何在Spring Boot自定义文本内容并下载文件,现在他们又问了类似的问题,但这次更明确地提到要自定义txt文件的内容并下载。我需要确保回答准确,并且不要重复之前的内容,但可能需要更详细地针对txt文件进行说明。 首先,用户可能已经看过之前的回答,但可能还不太清楚如何具体应用到txt文件。或者他们可能需要更简化的步骤。我需要检查之前的回答是否已经涵盖了这种情况。在之前的回复中,我提到了使用字节数组、ResponseEntity和本地文件下载等方法,这些同样适用于txt文件。 不过,用户现在特别强调自定义txt内容,可能需要一个更直接的例子,比如动态生成文本内容然后下载为txt文件。需要确保示例代码是专门针对txt文件的,包括正确的内容类型设置和文件名设置。 另外,用户可能对如何构建文本内容有疑问,比如如何换行、处理编码问题等。在注意事项中,我需要强调UTF-8编码的重要性,以及如何处理中文文件名的问题,避免乱码。 可能还需要提到不同的方法之间的区别,比如直接操作HttpServletResponse和使用ResponseEntity的优势,比如后者更符合Spring的惯例,代码更简洁,可测试性更好。 需要检查是否有遗漏的关键点,例如设置Content-Disposition头部,正确关闭流,以及如何处理大文件的情况。不过由于用户提到的是自定义内容,可能内容不会太大,但还是要提到最佳实践,比如使用缓冲流。 另外,用户可能是在开发某个需要生成报告或日志下载的功能,所以示例中的动态内容部分可能需要更贴近实际应用,比如添加时间戳或用户特定的数据。 最后,确保回答结构清晰,分步骤说明,让用户能一步步跟随操作,同时提供不同的方法选项,方便他们根据项目需求选择。</think>在 Spring Boot 中实现动态生成 TXT 文件内容并下载,可通过以下三种典型方式实现(含完整代码示例和最佳实践): --- ### 一、基础版:直接操作 HttpServletResponse ```java @GetMapping("/download/direct") public void downloadDirect(HttpServletResponse response) throws IOException { // 动态生成文本内容(示例:带时间戳的日志) String content = "=== 动态生成内容 ===\n" + "时间: " + LocalDateTime.now() + "\n" + "内容: 这是动态生成的TXT文件\n" + "行尾测试:Windows换行\r\n 和Linux换行\n"; // 必须设置响应头 response.setContentType("text/plain; charset=UTF-8"); // MIME类型 response.setCharacterEncoding("UTF-8"); // 编码强制指定 response.setHeader("Content-Disposition", "attachment; filename=\"dynamic-content.txt\""); // 使用try-with-resources自动关闭流 try (PrintWriter writer = response.getWriter()) { writer.write(content); } // 不需要手动flush/close } ``` --- ### 二、进阶版:使用 ResponseEntity(推荐) ```java @GetMapping("/download/entity") public ResponseEntity<byte[]> downloadByEntity() { // 动态构建内容(示例:CSV格式转TXT) StringBuilder sb = new StringBuilder(); sb.append("ID,Name,Email\n"); sb.append("1,张三,zhangsan@example.com\n"); sb.append("2,李四,lisi@example.com\n"); // 处理中文文件名(防止乱码) String fileName = "用户数据.txt"; String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8) .replace("+", "%20"); return ResponseEntity.ok() .header(HttpHeaders.CONTENT_TYPE, "text/plain; charset=UTF-8") .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + encodedFileName) .body(sb.toString().getBytes(StandardCharsets.UTF_8)); } ``` --- ### 三、专业版:结合 Resource 接口 ```java @GetMapping("/download/resource") public ResponseEntity<Resource> downloadResource() { // 动态生成内容(示例:带随机数的测试文件) String content = IntStream.range(0, 50) .mapToObj(i -> "随机数 " + i + ": " + (int)(Math.random()*100)) .collect(Collectors.joining("\n")); // 创建内存中的资源文件 ByteArrayResource resource = new ByteArrayResource(content.getBytes(StandardCharsets.UTF_8)); return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"random-numbers.txt\"") .contentType(MediaType.TEXT_PLAIN) .contentLength(resource.contentLength()) .body(resource); } ``` --- ### 四、企业级最佳实践 #### 1. 使用模板引擎动态生成 ```java @Autowired private TemplateEngine templateEngine; // Thymeleaf 或 FreeMarker @GetMapping("/download/template") public ResponseEntity<Resource> templateDownload() { // 构建数据模型 Map<String, Object> model = new HashMap<>(); model.put("title", "系统报告"); model.put("generationDate", LocalDate.now()); model.put("items", Arrays.asList("错误日志", "访问记录", "性能数据")); // 渲染模板 String content = templateEngine.process("report-template.txt", new Context(Locale.CHINA, model)); // 返回资源 return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"系统报告.txt\"") .body(new ByteArrayResource(content.getBytes(StandardCharsets.UTF_8))); } ``` #### 2. 大文件流式处理 ```java @GetMapping("/download/large-file") public ResponseEntity<StreamingResponseBody> streamDownload() { // 创建流式响应体 StreamingResponseBody stream =
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值