1

I have this Spring component which I want to call from several locations in Java web application:

@Component
public class NotificationListener {

    public void notificationProcess(TransactionsBean ro) {

        // some code
    }    
}

Can I use it as a normal object in Spring or I should use other way to call the Spring code?

Peter Penzov
  • 1,126
  • 134
  • 430
  • 808
  • It's just a class, and doesn't seem to have any dependencies, so you could easily `new` an instance up and call its methods outside of any Spring context. Did you try that? What happened? – jonrsharpe Aug 11 '18 at 21:45
  • Note that if you do call it from outside of the application context, any autowiring will *not* take place. – filpa Aug 11 '18 at 21:48
  • ok, is there a way to call it as a component? – Peter Penzov Aug 11 '18 at 21:48
  • What do you mean *"as a component"*? What do you mean *"as a normal object"*? It's not clear to me what the problem is. – jonrsharpe Aug 11 '18 at 21:50
  • If the other code that wants to call on this object is also within Spring components, then you would just @Autowire a reference to this one from those others. If the code is outside Spring components, then this might help: https://stackoverflow.com/questions/129207/getting-spring-application-context – moilejter Aug 12 '18 at 00:58

1 Answers1

1

What you can do is retrieve the current ApplicationContext by implementing ApplicationContextAware and lookup the bean yourself with getBean.

Another thing you can try is autowire like you're used to with @Autowired and then use the following utility from Spring:

SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);

KenCoenen
  • 475
  • 3
  • 8