最近研究spinrg(mvc)+openjpa,相比Struts2来说SpringMVC最郁闷的是国际化资源文件的配置,不知道是我不会还是什么原因,必须要一个一个写。看了源代码貌似也没有提供批量导入的方法,所以尝试着进行了一些修改。因为没有仔细研究Spring的代码,只简单改了一下,效率等方面可能考虑的不多,但我主要用在WEB部分,只在启动的时候加载,效率也不会有太大的影响。少说 上代码
xml配置
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basename" value="/WEB-INF/classes/com/strong/messages/messages" /> <property name="cacheSeconds" value="0" /> </bean>
可以看出要修改的就是“org.springframework.context.support.ReloadableResourceBundleMessageSource”,我重建了一个class:com.strong.utils.spring.ReloadableResourceBundleMessageSource,修改部分代码:
public void setBasenames(String[] basenames) {
if (basenames != null && basenames.length > 0) {
String strWebPath = this.getClass().getClassLoader().getResource("../../").getPath();
String strBasePath = strWebPath + basenames[0];
try {
List<File> listFile = FileUtils.getSuoYouWenJianLuJing(strBasePath);
List<String> listFile1 = new ArrayList<String>();
for (File file : listFile) {
if (!file.isDirectory() && file.getName().indexOf("_") == -1 && file.getName().indexOf(".properties") > -1) {
listFile1.add(file.getAbsolutePath().replace(strWebPath, "").replace(".properties", ""));
}
}
this.basenames = new String[listFile1.size()];
for (int i = 0; i < listFile1.size(); i++) {
this.basenames[i] = listFile1.get(i).trim();
System.out.println("load properties file: " + listFile1.get(i).trim());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// this.basenames = new String[basenames.length];
// for (int i = 0; i < basenames.length; i++) {
// String basename = basenames[i];
// Assert.hasText(basename, "Basename must not be empty");
// this.basenames[i] = basename.trim();
// System.out.println(basename);
// }
} else {
this.basenames = new String[0];
}
}
为了尽可能的减少耦合的部分,只是在这里把从list中获取资源文件数组改为只获取第一个,并遍历这个目录将其中的所有properties扩展名且不含_的文件的相对路径增加到basenames中,其他的都不改变。遍历文件目录的代码:
public static List<File> getSuoYouWenJianLuJing(String strLuJing) throws IOException {
if (strLuJing == null || strLuJing.length() == 0) {
return null;
}
File fileLuJing = new File(strLuJing);
if (!fileLuJing.exists()) {
return null;
}
return getSuoYouWenJianLuJing(fileLuJing);
}
重新修改XML文件如下:
<bean id="messageSource" class="com.strong.utils.spring.ReloadableResourceBundleMessageSource">
<property name="basenames" value="WEB-INF/classes/com/strong" />
<property name="cacheSeconds" value="0" />
</bean>
OK 完工,代码写的非常粗糙,并且也只修改了ReloadableResourceBundleMessageSource类,不过大概意思和思路已经差不多了,至于使用通配符获取资源文件例如 /WEB-INF/classes/com/strong/*/messages等就类似了