我有一个spring项目名称:SpringExample
目录结构:
spring的locale.xml:
<bean id="customerService" class="com.mkyong.customer.services.CustomerService" />
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename">
<value>\SpringExample\conf\messages</value>
</property>
</bean>
CustomerService的代码:
package com.mkyong.customer.services;
public class CustomerService implements MessageSourceAware
{
private MessageSource messageSource;
public void setMessageSource(MessageSource messageSource) {
this.messageSource = messageSource;
}
public void printMessage(){
String name = messageSource.getMessage("customer.name",
new Object[] { 28, "http://www.mkyong.com" }, Locale.US);
System.out.println("Customer name (English) : " + name);
}
app类(主类)的代码:
package com.mkyong.common;
import java.util.Locale;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.mkyong.customer.services.CustomerService;
public class App {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "locale.xml" });
// get the message resource inside context
String name = context.getMessage("customer.name", new Object[] { 28,
"http://www.mkyong.com" }, Locale.US);
System.out.println("Customer name (English) : " + name);
// get the message resource inside the bean
CustomerService cust = (CustomerService) context
.getBean("customerService");
cust.printMessage();
}
}
但它无法捆绑proprtie文件,因为它不在包中。 我得到例外:
警告:找不到ResourceBundle [\ SpringExample \ conf?\ messages] MessageSource:找不到基本名称的包 \ SpringExample \ conf?\ messages,locale en_US
如何将它与外部文件夹资源捆绑在一起?就像我的例子一样?
答案 0 :(得分:3)
将conf
目录设为maven资源目录(maven build helper plugin)或将文件从conf
移至src\main\resources
。然后修改ResourceBundleMessageSource
以从类路径根加载消息,因为src\main\resources
对应于类路径根。
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename">
<value>messages</value>
</property>
</bean>
注意:如果您使用ReloadableResourceBundleMessageSource
代替ResourceBundleMessageSource
,则必须使用前缀classpath:
作为basename
属性值classpath:messages
)