如何从Spring Java配置@Configuration类从WEB-INF获取资源? [英] How to get resources from WEB-INF from Spring java configuration @Configuration class?

查看:75
本文介绍了如何从Spring Java配置@Configuration类从WEB-INF获取资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在春季之一创建 @Bean 的过程中将特定资源加载到 WEB-INF 目录下 @Configuration 类。

I am trying to load specific resource under WEB-INF directory during @Bean creation in one of the Spring @Configuration classes.

据我所知 @ImportResource 仅用于Spring xml配置,而不用于其他文件。
使用 ClassLoader 的方法不起作用,并且始终返回 null

As I know @ImportResource is used only for Spring xml configurations and not for other files. Approaches with ClassLoader don't work and always return null.

例如:

    @Bean
    public aBean someBean() {
        final URL someFolderDirUrl = WebConfig.class.getClassLoader().getResource("WEB-INF/someFolder");
        final URL someFolderDirUrl2 = WebConfig.class.getClassLoader().getResource("/someFolder");
        final URL someFolderDirUrl3 = WebConfig.class.getClassLoader().getResource("/WEB-INF/someFolder");
        final URL someFolderDirUrl4 = WebConfig.class.getClassLoader().getResource("someFolder");

        // final URI someFolderDirUri = new URI("file:/WEB-INF/someFolder");

        if(modulesDirUrl != null) {
            File someFolderDirFile;
            try {
                someFolderDirFile = new File(someFolderDirUrl.toURI());
            } catch(final URISyntaxException e) {
                someFolderDirFile = new File(someFolderDirUrl.getPath());
            }

            return new aBean(someFolderDirFile);
        }

        return new aBean();
    }

最后,所有 someFolderDirUrlX 变量都是 null ,与 someFolderDirUri 相同。

At the end all someFolderDirUrlX variables are null, the same for someFolderDirUri.

是否可以在Spring的 @Configuration 类中获得一个 File 对象,该对象指向 WEB-中的文件或目录。 INF

Is it possible to get a File object inside Spring's @Configuration class which points to file or directory inside WEB-INF?

推荐答案

您可以从ServletContext中访问它:

You could access this from the ServletContext:

@Autowired
ServletContext servletContext;

@Bean
public aBean someBean() {
     File someFolderDirUrl = new File( servletContext.getRealPath("/WEB-INF/") );
     ....
}

这篇关于如何从Spring Java配置@Configuration类从WEB-INF获取资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆