Accessing a Spring bean from a static context is problematic because the initialization of beans isn't tied to their construction, and Spring may instrument injected beans by wrapping them in proxies; simply passing around references to this
will often result in unexpected behaviour. It's best to rely on Spring's injection mechanism.
If you really have to do it (perhaps because you need access from legacy code), use something like this:
@Service
public class A implements ApplicationContextAware {
private static final AtomicReference<A> singleton;
private static final CountDownLatch latch = new CountDownLatch(1);
@Resource
private MyInjectedBean myBean; // inject stuff...
public static A getInstance() {
try {
if (latch.await(1, TimeUnit.MINUTES)) {
return singleton.get();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
throw new IllegalStateException("Application Context not initialized");
}
@Override
public void setApplicationContext(ApplicationContext context) {
singleton.set(context.getBean(A.class));
latch.countDown();
}
}