How to get resources from WEB-INF from Spring java

2019-09-18 19:28发布

问题:

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

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.

For example:

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

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

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

回答1:

You could access this from the ServletContext:

@Autowired
ServletContext servletContext;

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