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 配置项

  1. 通过 @Value("${config.key.name}");
  2. 通过 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");
    }
}

参考链接: Read values from properties file in Spring

posted @ 2017-04-08 00:12  whilst  阅读(159)  评论(0编辑  收藏  举报