Reputation: 1279
I have a Spring 3 project which acts as a Rest API, and wanted to wire a spring bean I have into an unmanaged class for logging purposes.
After trying many different things, what worked was marking my unmanaged class with the annotation @Configurable
.
Like:
@Configurable
public class ClassNotManagedBySpring {
@Autowired
@Qualifier("myBean")
private MyBean myBean;
}
@Service("myBean")
public class MyBean {
@Autowired
@Qualifier("someOtherBean")
private SomeOtherBean someOtherBean;
}
And then in my beans.xml:
<context:spring-configured/>
So now let's say that ClassNotManagedBySpring.java
, is one of 6 classes that all do something similar, except 3 of them ARE managed by spring because they have the @Component
annotation.
But all 6 of these classes need to @Autowire
MyBean.java
and only some need the @Configurable
annotation.
To note, I was already previously using AspectJ in this app for multiple other purposes.
I want to know what is the risk in my spring application by all of a sudden wiring spring managed dependencies into un managed classes in this way?
Can there be performance issues? Risks of errors at runtime?
If this isn't the best way of wiring a spring managed bean into an unmanaged class, what is?
Upvotes: 1
Views: 637
Reputation: 7098
I've been using @Configurable
for years without issues, it's a very easy solution if you need app instantiated beans configured by Spring. My use cases were all in the UI tier. I also used @Configurable(preConstruction = true)
whenever I needed autowired values already in the constructor. Of course, if you make millions of @Configurable
objects it might be a performance issue, otherwise I wouldn't worry too much about it. The only small aesthetic problem I had was Eclipse giving me some red underlines at class definitions extending @Configurable
classes, complaining that the hierarchy of class SomeClass is inconsistent, but it compiled them nevertheless, no errors in the Problems view or at runtime whatsoever.
Upvotes: 1