1

I have created an application using Java Swing. Now, i want to integrate Spring Autowiring(Dependency Injection) in this application.

Doubt in mind is that to create UI(User Interface), i would be using "new" keyword, but to use DAO and POJO classes, i want them to auto-wired.

Can somebody suggest and help me out.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • You'll need to do some refactoring to allow Spring to manage the SWING components same as the DAOs and POJOs. See [here](http://stackoverflow.com/questions/3718671/swing-gui-development-with-spring) which has a link to an old tutorial. Just translate the xml based configuration to annotations. – Andrew S Sep 06 '16 at 13:59
  • Thanks a lot @AndrewS . It helped me.. – Gagandeep Singh Sep 07 '16 at 06:18

1 Answers1

3

Not sure if I understood you right. I assume, that you want to autowire your DAOs, Services etc. in UI classes. But in order do to that, these UI classes would have to be Spring Beans themselves.

What you could do, is to register each UI class in the Spring application context, when its created. To do that, you could create the following class:

public class BeanProvider {

    private static ApplicationContext applicationContext;

    /**
     * Autowires the specified object in the spring context
     * 
     * @param object
     */
    public static void autowire(Object object) {
        applicationContext.getAutowireCapableBeanFactory().autowireBean(object);
    }

    @Autowired
    private void setApplicationContext(ApplicationContext applicationContext) {
        BeanProvider.applicationContext = applicationContext;
    }

}

and then in the constructor of each UI class:

public MyUiClass(){
BeanProvider.autowire(this);
}
aebblcraebbl
  • 151
  • 7
  • Cool..I 'll definitely follow this..and reply asap with some outcomes...Thanks a lot @aebblcraebbl – Gagandeep Singh Sep 09 '16 at 11:43
  • 1
    It's necessary to put a @Component above BeanProvider class. After this modification, the code worked for me. Thank you for that. – Carlos Nantes Apr 09 '18 at 19:52
  • After setting `System.setProperty("java.awt.headless", "false");` in my code, it worked as expected but when trying to build a jar file it returned to giving me the `java.awt.HeadlessException: null`, so this was a problem again. However, this bit of code saved my life :D after hours of research and experiments. This worked like a charm!! Thanks bro. – Damoiskii Apr 24 '23 at 18:01