0

I need to create dynamic beans at runtime with different classes for different conditions using a dynamic bean factory. It's for generic DAO Implementation.How to implement it using Java configuration??

MVC Initializer Class

Using prototype bean configuration

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class SpringMvcInitializer implements WebApplicationInitializer {
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
        appContext.register(AppConfig.class);
     /*   serviceA.setEntityClass((Class<?>) Education.class);
        IGenericDao ff=appContext.getBean(IGenericDao.class,"IGenericDao");*/

        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("SpringDispatcher", new DispatcherServlet(appContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");

        appContext.setServletContext(servletContext);
        appContext.refresh();
        //appContext.getBean("IGenericDao");
       // Services serviceA = new Services(Education.class);
        Services<?> serviceA = (Services<?>)appContext.getBean("IGenericDao");
        serviceA.setEntityClass((Class<?>) Education.class);
        // serviceA = (Services)appContext.getBean("IGenericDao");
        //serviceA.setEntityClass((Class<?>) Education.class);
       // serviceA.setEntityClass(Employee.class);
        serviceA.setName("hellooo");
        serviceA.getName();

        //appContext.
        //serviceA=new Services(T clazz);
    }
}
kryger
  • 12,906
  • 8
  • 44
  • 65
Amritha Ashok
  • 55
  • 1
  • 10
  • You should include more details and show your failed efforts to make it easier to understand what you're trying to achieve. – kryger Aug 25 '16 at 11:23

1 Answers1

2

Try this code,

    BeanDefinitionRegistry beanFactory = (BeanDefinitionRegistry) appContext.getBeanFactory();
    beanFactory.registerBeanDefinition("IGenericDao",
            BeanDefinitionBuilder.genericBeanDefinition(Employee.class)           
                    .getBeanDefinition()
    );  
LearnCode Master
  • 552
  • 2
  • 8
  • 25