2016-08-25 6 views
0

動的Beanファクトリを使用して、さまざまな条件の異なるクラスを使用して実行時に動的Beanを作成する必要があります。それはジェネリックDAO Implementation.Howの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

どのように動作するかを詳しく説明できますか? –

関連する問題