场景:在应用程序中,我有依赖于语言的属性文件,这些文件用作生成电子邮件的模板:
email-subscription_en.properties
:
email.subject=You are successfully subscribed to list {0}
email.body=...
email-cancellation_en.properties
:
email.subject=You are successfully unsubscribed from list {0}
email.body=...
等等。现在在Spring上下文中我想拥有这些包:
<bean id="subscriptionMailProperties" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="org.company.email-subscription" />
</bean>
<bean id="cancellationMailProperties" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="org.company.email-cancellation" />
</bean>
与这些与语言无关的常见属性合并,我希望在上下文中声明:
<util:properties id="commonMailProperties">
<prop key="email.from">noreply@company.org</prop>
<prop key="email.to">{0}@company.org</prop>
</util:properties>
怎么可能?
答案 0 :(得分:1)
据我所知,没有人支持。您正在尝试将配置与资源包混合使用。我觉得你现在拥有的是正确的。如果你没有保持原样的奢侈,这是一种方式(更多的是黑客)
使用'commonMailProperties'(java.util.Properties)作为依赖项实现org.springframework.context.MessageSource
,并将bean id称为'commonMessageSource'。
在'getMessage'实现中从'commonMailProperties'获取值。
为'parentMessageSource'属性将'commonMessageSource'注入'subscriptionMailProperties'和'cancellationMailProperties'。
答案 1 :(得分:0)
如果有人对完整的解决方案感兴趣:
创建课程PropertiesMessageSource
:
/**
* {@link org.springframework.context.MessageSource} implementation that resolves messages via underlying
* {@link Properties}.
*/
public class PropertiesMessageSource extends AbstractMessageSource {
private Properties properties;
/**
* Set properties to use.
*/
public void setProperties(Properties properties) {
this.properties = properties;
}
@Override
protected MessageFormat resolveCode(String code, Locale locale) {
String property = properties.getProperty(code);
if (property == null) {
return null;
}
return createMessageFormat(property, locale);
}
}
使用它:
<bean id="commonMailProperties" class="org.company.PropertiesMessageSource">
<property name="properties">
<props>
<prop key="email.from">noreply@company.org</prop>
<prop key="email.to">{0}@company.org</prop>
</props>
</property>
</bean>
<bean id="subscriptionMailProperties" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="org.company.email-subscription" />
<property name="parentMessageSource">
<ref bean="commonMailProperties"/>
</property>
</bean>
答案 2 :(得分:0)
ResourceBundleMessageSource
(更准确地说:AbstractMessageSource
的所有后代)现在具有commonMessages
属性,该属性可以保存与区域无关的值。例如,当您希望邮件主题和正文区域设置相关时,某些属性(来自邮件和邮件)在所有包中都是通用的(请检查SPR-10291):
<bean id="mailProperties" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="org.mycompany.email" />
<property name="commonMessages">
<props>
<prop key="email.from">empty@mydomain.org</prop>
<prop key="email.to">%s@mydomain.org</prop>
</props>
</property>
</bean>