user3385957
user3385957

Reputation: 141

inject spring bean in a class not instantiated by spring

I have a class called FileReader which I explicitly instantiate each time a new file gets generated. I would like to have a centrally managed singleton ExecutorService which gets inserted into FileReader each time I instantiate it. This executorservice is a singleton managed by Spring. I was wondering if it is possible to inject it (using autowiring or something like that) in each new instance of FileReader as I create it explicitly (using something like FileReader fr = new FileReader() )

Upvotes: 1

Views: 533

Answers (1)

gpeche
gpeche

Reputation: 22514

You can check about dependency injection of domain objects with Spring, the approach would be the same. You would need to enable load-time weaving for your project, though.

If you are not planning on doing this kind of thing very often, I suggest:

  • manual injection, as @JB Nizet commented above, or
  • define FileReader as a prototype bean, and change your new FileReader() occurrences to applicationContext.getBean("fileReader") or equivalent. Then you can inject whatever you want into FileReader via "plain" Spring. Personally I would encapsulate that getBean() invocation inside a FileReaderFactory, to avoid hard dependencies to Spring in my business classes.

Upvotes: 1

Related Questions