Gagandeep Singh
Gagandeep Singh

Reputation: 33

can we implement Spring Autowiring in Java Standalone Application (Swing)

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.

Upvotes: 1

Views: 685

Answers (1)

aebblcraebbl
aebblcraebbl

Reputation: 151

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);
}

Upvotes: 3

Related Questions