Spring: Inject URL for classpath resource

后端 未结 4 658
野性不改
野性不改 2021-01-11 09:53

I want to inject the URL of a classpath resource in a way that does not create a dependency on Spring in the Bean. Meaning, the bean should not use Spring\'s interfaces/clas

相关标签:
4条回答
  • 2021-01-11 10:17

    Spring is able to convert classpath:... values into java.net.URL implicitly:

    public class Foo {
        private URL url;
        ...
    }
    

    .

    <bean class = "Foo">
        <property name = "url" value = "classpath:..." />
    </bean>
    
    0 讨论(0)
  • 2021-01-11 10:19

    Following on from axtavt's answer, if you will allow yourself Spring annotations in the bean, you can do it like this:

    @Value("classpath:myClasspathLocation") private URL url;
    
    0 讨论(0)
  • 2021-01-11 10:19

    create your own implementation of a spring resource by extending the org.springframework.core.io.ClassPathResource like MyClasspathResource extends ClassPathResource and inject this type into your bean. Like this you do not have any dependency to spring and can later reimplement your resource with something else.

    <bean class="myBean">
     <property name="classPathType">
      <bean class="org.test.bla.MyClasspathResource">
       <constructor-arg index="0" value="classpath:/org/test/bla/MyUrl" />
      </bean>
     </property>
    </bean>
    
    0 讨论(0)
  • 2021-01-11 10:33

    There is hardly anything non-spring that's equivalent to Spring's resource concept.

    You could for example use Guava's InputSupplier as an alternative, but you are missing powerful standard spring features if you do.

    0 讨论(0)
提交回复
热议问题