【问题标题】:Spring DI: Injection of FileInputStream in Constructor using annotationSpring DI:使用注解在构造函数中注入 FileInputStream
【发布时间】:2014-10-20 15:44:47
【问题描述】:

我想使用 spring 注释注入 FileInputStream 作为构造函数参数。 假设我有以下类(在进行构造函数 arg 注入之前)

@Component
public class MyClass{

    private BlaClass xy;


    public MyClass(InputStream is)
    {
     this.xy = new BlaClass(is);
    }

}

所以现在我的问题是我是否可以使用@Value 注释或类似的注释来注入输入流?应该是这样的:

@Component
public class MyClass{

    private BlaClassTakingAnInputStream xy;

    //this is of course not correct
    public MyClass(@Value("classpath:path/to/a/file") is)
    {
     this.xy = new BlaClassTakingAnInputStream(is);
    }

}

p.s.:我知道它是如何使用 xml 配置工作的,但我想使用注释来完成它,因为它不那么冗长。

【问题讨论】:

  • 您不应该在类路径上获得FileInputStream 资源。你想做什么?
  • 你是对的 Sotirios。其实我想获取资源,然后执行“resource.getInputStream()”。

标签: java spring spring-mvc dependency-injection


【解决方案1】:

你可以像这样使用Resource

@Autowired
public MyClass(@Value("classpath:path/to/a/file") Resource resource) {
    // access to resource input stream
}

请注意,@Autowired 需要将此构造函数标记为要使用的构造函数。否则,Spring 会寻找无参数的构造函数。

【讨论】:

  • 谢谢。这就是我一直在寻找的。对不起,我以错误的方式提出的问题;-)
猜你喜欢
  • 2017-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-29
  • 1970-01-01
相关资源
最近更新 更多