Add the resource file to the Spring bean

How can I add some file resource to a spring bean? Now I am autowire ServletContext and use as shown below. Is this a more elegant way to do this in Spring MVC?

@Controller
public class SomeController {

    @Autowired
    private ServletContext servletContext;

    @RequestMapping("/texts")
    public ModelAndView texts() {
        InputStream in = servletContext.getResourceAsStream("/WEB-INF/file.txt");
        // ...
    }
}
+5
source share
3 answers

Something like that:

@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();
    }
}

In the definition of bean:

<bean id="..." class="x.y.SomeController">
   <property name="resource" value="/WEB-INF/file.txt"/>
</bean>

This will create ServletContextResourceusing the path /WEB-INF/file.txtand add it to your controller.

Note. You cannot use component scanning to detect your controller using this technique, you need to explicitly define a bean.

+5
source

What are you going to use the resource for? In this example, you are not doing anything.

, , , /, MessageSource.

beans (, 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 . autwire 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" />

- .

+1

Or just use the annotation @Value.

For a single file:

@Value("classpath:conf/about.xml")
private Resource about;

For multiple files:

@Value("classpath*:conf/about.*")
private Resource[] abouts;
0
source

All Articles