2016-08-25 90 views
0

我需要在運行時使用動態bean工廠創建動態bean,使用不同的類爲不同的條件創建動態bean。這是通用的DAO實現。如何使用Java配置實現它?如何在Spring MVC的不同類中創建動態bean

MVC初始化器類

使用原型bean配置

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

你應該包括更多的細節,並且你失敗的努力,使之更容易瞭解你正在努力實現。 – kryger

+0

已編輯的問題。 –

回答

1

試試這個代碼,

BeanDefinitionRegistry beanFactory = (BeanDefinitionRegistry) appContext.getBeanFactory(); 
    beanFactory.registerBeanDefinition("IGenericDao", 
      BeanDefinitionBuilder.genericBeanDefinition(Employee.class)   
        .getBeanDefinition() 
    ); 
+0

謝謝......它的工作。 –

+0

你能詳細說明它是如何工作的嗎? –