简体   繁体   English

Spring:为类路径资源注入URL

[英]Spring: Inject URL for classpath resource

I want to inject the URL of a classpath resource in a way that does not create a dependency on Spring in the Bean. 我想以一种不在Bean中创建对Spring的依赖的方式注入类路径资源的URL。 Meaning, the bean should not use Spring's interfaces/classes. 意思是,bean不应该使用Spring的接口/类。 How can I do that? 我怎样才能做到这一点?

Spring is able to convert classpath:... values into java.net.URL implicitly: Spring能够隐式地将classpath:...值转换为java.net.URL

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

.

<bean class = "Foo">
    <property name = "url" value = "classpath:..." />
</bean>

从axtavt的回答开始,如果你允许自己在bean中使用Spring注释,你可以这样做:

@Value("classpath:myClasspathLocation") private URL url;

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. 通过扩展org.springframework.core.io.ClassPathResource来创建自己的spring资源实现,如MyClasspathResource扩展ClassPathResource并将此类型注入到bean中。 Like this you do not have any dependency to spring and can later reimplement your resource with something else. 像这样,你对spring没有任何依赖,以后可以用其他东西重新实现你的资源。

<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>

There is hardly anything non-spring that's equivalent to Spring's resource concept . 几乎没有任何非弹簧相当于Spring的资源概念

You could for example use Guava 's InputSupplier as an alternative, but you are missing powerful standard spring features if you do. 例如,您可以使用GuavaInputSupplier作为替代方案,但如果您这样做,则缺少强大的标准弹簧功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM