我正在创建一个简单的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
。我无法从属性文件中获取值。
任何帮助将不胜感激......
答案 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