在spring boot中访问属性文件

时间:2016-10-22 10:10:32

标签: spring-boot properties-file

我正在创建一个简单的spring启动应用程序,我正在尝试访问外部config.properties文件。

IndexController.java

@Controller
public class IndexController {

    XmlOperation xmlOperation = new XmlOperation();

    @RequestMapping("/")
    public String greeting() {
        return "greeting";
    }

    @RequestMapping(params = "btnOpen", method = RequestMethod.POST)
    public String uploadFile(@RequestParam("file") MultipartFile file, Model model) {
        try {
            InputStream is = file.getInputStream();
            model.addAttribute("fileContent", xmlOperation.readXml(is));
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        return "greeting";
    }
}

XmlOperation.java

@PropertySource("classpath:config.properties")
public class XmlOperation {

    @Autowired
    Environment env;

    public String readXml(InputStream is) throws IOException {
        System.out.println(env.getProperty("filepath"));
        StringWriter writer = new StringWriter();
        IOUtils.copy(is, writer, StandardCharsets.UTF_8);
        String fileContent = writer.toString();
        return fileContent;

    }

config.properties文件位于src/main/resources。我无法从属性文件中获取值。

任何帮助将不胜感激......

1 个答案:

答案 0 :(得分:1)

src/main/resources中的XmlOperation xmlOperation = new XmlOperation();文件正常,但为什么要初始化:

IndexController

XmlOperation中的

?而且我也不确定@PropertySource是否是spring组件(问题中你只有XmlOperation超过XmlOperation。)

基本上我会将@Component作为 spring IndexController,并且IoC会将此组件注入public String readXml(InputStream is)

XmlOperation中的

filepath表现得像标准服务,我会创建属性config.properties并使用@Value注释从配置文件(@Controller public class IndexController { @Autowired private XmlOperation xmlOperation; @RequestMapping("/") public String greeting() { return "greeting"; } @RequestMapping(params = "btnOpen", method = RequestMethod.POST) public String uploadFile(@RequestParam("file") MultipartFile file, Model model) { try { InputStream is = file.getInputStream(); model.addAttribute("fileContent", xmlOperation.readXml(is)); } catch (IOException e) { System.out.println(e.getMessage()); } return "greeting"; } } )注入值。 / p>

完整示例:

@Component
@PropertySource("classpath:config.properties")
public class XmlOperation {

    // use this when XmlOperation is @Configuration bean and you want to create @Bean-s e.g
    // @Autowired
    // Environment env;

    // for your case inject property like this
    @Value("${filepath}")
    private String filepath;

    public String readXml(InputStream is) throws IOException {

        // dont use this
        //System.out.println(env.getProperty("filepath"));

        // rather this
        System.out.println(filepath);

        StringWriter writer = new StringWriter();
        IOUtils.copy(is, writer, StandardCharsets.UTF_8);
        String fileContent = writer.toString();
        return fileContent;

    }
}
TheHeadHTML