SpringBoot Tips
读取资源文件
@RestController
@EnableAutoConfiguration
public class ResourcesController {
@Autowired
private ResourceLoader resourceLoader;
@RequestMapping(value = "/get-resources", method = RequestMethod.GET)
public String getResources() throws IOException {
String content = IOUtils.toString(resourceLoader.getResource("classpath:test.txt").getInputStream(), "UTF-8");
return "the content of resources:" + content;
}
public static void main(String[] args) {
SpringApplication.run(ResourcesController.class, args);
}
}
参考链接: Spring Boot get resource file example
获取 properties
配置项
- 通过
@Value("${config.key.name}")
; - 通过
Environment
bean;
@Controller
@Configuration
@PropertySource("classpath:system.properties")
public class SimpleController {
@Value("${server.address}")
private String serverAddress;
@Autowired
private Environment env;
@RequestMapping("/test-configuration-annotation")
@ResponseBody
public String testProperties() {
return "serverAddress: " + env.getProperty("server.address") +
" serverPort: " + env.getProperty("server.port");
}
}