java Spring:为类路径资源注入 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4578402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 07:02:05  来源:igfitidea点击:

Spring: Inject URL for classpath resource

javaspring

提问by IttayD

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/classes. How can I do that?

我想以一种不会在 Bean 中创建对 Spring 的依赖的方式注入类路径资源的 URL。意思是,bean 不应该使用 Spring 的接口/类。我怎样才能做到这一点?

采纳答案by axtavt

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

Spring 能够将classpath:...java.net.URL隐式转换为:

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

.

.

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

回答by Daniel Alexiuc

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

继 axtavt 的回答之后,如果您允许自己在 bean 中使用 Spring 注释,您可以这样做:

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

回答by guido

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.

通过扩展 org.springframework.core.io.ClassPathResource 来创建你自己的 spring 资源实现,比如 MyClasspathResource extends ClassPathResource 并将这个类型注入到你的 bean 中。像这样,您对 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>

回答by Sean Patrick Floyd

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

几乎没有任何非 spring 等同于Spring 的资源概念

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

例如,您可以使用GuavaInputSupplier作为替代方案,但如果这样做,您将缺少强大的标准弹簧功能。