Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从Spring java configuration@configuration类从WEB-INF获取资源?_Java_Spring_Spring Mvc_Configuration - Fatal编程技术网

如何从Spring java configuration@configuration类从WEB-INF获取资源?

如何从Spring java configuration@configuration类从WEB-INF获取资源?,java,spring,spring-mvc,configuration,Java,Spring,Spring Mvc,Configuration,在Spring@Configuration类的@Bean创建过程中,我正在尝试加载WEB-INF目录下的特定资源 据我所知,@ImportResource仅用于SpringXML配置,而不用于其他文件。 使用ClassLoader的方法不起作用,并且总是返回null 例如: @Bean public aBean someBean() { final URL someFolderDirUrl = WebConfig.class.getClassLoader().ge

在Spring
@Configuration
类的
@Bean
创建过程中,我正在尝试加载
WEB-INF
目录下的特定资源

据我所知,
@ImportResource
仅用于SpringXML配置,而不用于其他文件。 使用
ClassLoader
的方法不起作用,并且总是返回
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
相同


是否可以在Spring的
@配置
类中获取指向
WEB-INF
中的文件或目录的
文件
对象

@Autowired
ServletContext servletContext;

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

注入一个
ResourceLoader
来利用Spring的资源加载机制,而不是在自己周围进行黑客攻击。不要使用
ClassLoader
getResource
用于类路径资源
WEB-INF
通常不放在类路径上。