[英]Initialize spring beans programmatically
在辦公室,我們正在制作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將嘗試自動裝配@ComponentScan中的所有bean,並且沒有找到會話工廠,因為稍后我將以這種野蠻的方式對其進行初始化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.