[英]Inject a file resource into Spring bean
将一些文件资源注入Spring bean的好方法是什么? 现在我自动装配ServletContext并使用如下所示。 在Spring MVC中更优雅的方式吗?
@Controller
public class SomeController {
@Autowired
private ServletContext servletContext;
@RequestMapping("/texts")
public ModelAndView texts() {
InputStream in = servletContext.getResourceAsStream("/WEB-INF/file.txt");
// ...
}
}
像这样的东西:
@Controller
public class SomeController {
private Resource resource;
public void setResource(Resource resource) {
this.resource = resource;
}
@RequestMapping("/texts")
public ModelAndView texts() {
InputStream in = resource.getInputStream();
// ...
in.close();
}
}
在你的bean定义中:
<bean id="..." class="x.y.SomeController">
<property name="resource" value="/WEB-INF/file.txt"/>
</bean>
这将使用/WEB-INF/file.txt
路径创建一个ServletContextResource
,并将其注入您的控制器。
请注意,您无法使用组件扫描来使用此技术检测控制器,您需要显式的bean定义。
或者只使用@Value
注释。
对于单个文件:
@Value("classpath:conf/about.xml")
private Resource about;
对于多个文件:
@Value("classpath*:conf/about.*")
private Resource[] abouts;
您打算如何使用该资源? 在你的例子中,你不做任何事情。
但是,从它的名称来看,您似乎正在尝试加载国际化/本地化消息 - 您可以为其添加MessageSource
。
如果您定义一些bean(可能在单独的messages-context.xml
),则类似于:
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>WEB-INF/messages/messages</value>
</list>
</property>
</bean>
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="en_GB" />
</bean>
Spring将在您启动应用程序时加载资源包。 然后,您可以将MessageSource
装入控制器并使用它来获取本地化消息:
@Controller
public class SomeController {
@Autowired
private MessageSource messageSource;
@RequestMapping("/texts")
public ModelAndView texts(Locale locale) {
String localisedMessage = messageSource.getMessage("my.message.key", new Object[]{}, locale)
/* do something with localised message here */
return new ModelAndView("texts");
}
}
NB。 将Locale
作为参数添加到控制器方法中将导致Spring神奇地将其连接到 - 这就是您需要做的所有事情。
然后,您还可以使用以下方法访问JSP中资源包中的消息:
<spring:message code="my.message.key" />
这是我的首选方式 - 看起来更干净。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.