在办公室,我们正在制作 spring maven Web 应用程序,并通过 WebApplicationInitializer 和 AnnotationConfigWebApplicationContext 设置它们。
我有一个任务涉及以编程方式初始化 Bean。
我一直在尝试使用 rootContext 来获取 bean 工厂并手动初始化自定义 bean,但它不起作用,它会告诉我在应用程序上下文中没有初始化具有该名称的 bean。
这是我的代码:
public void onStartup(ServletContext sc) throws ServletException {
AnnotationConfigWebApplicationContext rootContext
= new AnnotationConfigWebApplicationContext();
// my method for adding beans to root context
registerBeansManually(rootContext,
new Class<?>[]{MyEntity1.class, MyEntity2.class},
Map<String,String> mapReadFromSomewhere);
sc.addListener(new ContextLoaderListener(rootContext));
AnnotationConfigWebApplicationContext webContext
= new AnnotationConfigWebApplicationContext();
webContext.setParent(rootContext);
webContext.register(SpringWebConfig.class);
DispatcherServlet ds = new DispatcherServlet(webContext);
ServletRegistration.Dynamic registration = sc.addServlet("dispatcher1", ds);
registration.setLoadOnStartup(1);
registration.addMapping("/");
}
在另一种方法中,我尝试初始化 bean:
public void registerBeansManually(AnnotationConfigWebApplicationContext rootContext,
Class<?>[] entityClasses,
Map<String,String> dbInfoMap)
{
// get the bean factory from the root context
rootContext.refresh();
ConfigurableListableBeanFactory beenFactory = rootContext.getBeanFactory();
// in dbInfo map are the infor for connecting to db
// produce a DataSource instance and register it as a singleton bean :
DataSource ds = new DatabaseBeansProducer().produceDataSource(dbInfoMap);
beanFactory.registerSingleton("myProjectDataSource", ds);
// using the myProjectDataSource and the entity classes in the method argument
// produce a SessionFactory and register it as a singleton bean :
LocalSessionFactoryBean sf = new DatabaseBeansProducer().produceSessionFactory(ds, entityClasses);
beanFactory.registerSingleton("myProjectSessionFactory", sf);
// using the myProjectSessionFactory, produce the TransactionManager
// and register it as a singleton bean :
HibernateTransactionManager txm = new DatabaseBeansProducer().produceTransactionManager(sf);
beanFactory.registerSingleton("myProjectTransactionManager", txm);
}
就像我所说的,当我尝试以这种方式初始化它们时,我会遇到丢失 bean 的问题,即,我收到一条错误消息,指出我无法 @Autowire 'myProjectSessionFactory' bean,因为不存在具有该名称的 bean在应用程序上下文中。
我怎样才能做到这一点?
最佳答案
我明白了:
我所要做的就是在 myProjectSessionFactory bean 上添加以下注释:
@Autowired(required=false)
@Qualifier("myProjectSessionFactory")
private SessionFactory sessionFactory;
我对任何提示不在应用程序上下文中的 bean 执行相同的操作。
发生这种情况是因为当您执行
rootContext.refresh();
Spring 将尝试 Autowiring @ComponentScan 中的所有 bean,但它找不到 session 工厂,因为我稍后会以这种野蛮的方式初始化它。
关于java - 以编程方式初始化 spring bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48476155/