【问题标题】:How to create dynamic bean within different classes in Spring MVC如何在 Spring MVC 中的不同类中创建动态 bean
【发布时间】:2017-01-01 18:49:29
【问题描述】:

我需要在运行时使用动态 bean 工厂为不同条件创建具有不同类的动态 bean。是通用的DAO实现,如何使用Java配置实现??

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

【问题讨论】:

  • 你应该包含更多细节并展示你失败的努力,以便更容易理解你想要实现的目标。

标签: spring hibernate spring-bean hibernate-generic-dao


【解决方案1】:

试试这个代码,

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-04
    • 1970-01-01
    • 2017-01-13
    • 2017-11-24
    • 1970-01-01
    相关资源
    最近更新 更多