如何在 Spring MVC 中的不同 类 中创建动态 bean

How to create dynamic bean within different classes in Spring MVC

我需要在运行时使用动态 bean 工厂为不同的条件创建具有不同 类 的动态 bean。它用于通用 DAO Implementation.How 使用 Java 配置实现它??

MVC 初始化程序Class

使用原型 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);
    }
}

试试这个代码,

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