开发者

Spring with class.forname()

If an application is managed by the Spring container, can a develope开发者_StackOverflowr still use class.forName() to create an instance of a particular class? Or will that violate the Spring container and result in some exception?


Yes you can use it. The resulting object will not be managed by Spring, however.


If you are developing a web-application and assuming you have beans defined in applicationContext.xml then you can use:

ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());        
AnyBean anyBean = (AnyBean) applicationContext.getBean("anyBean");

where anyBean is the id of the bean defined in that xml. Though it will not create a new instance rather it will return an instance.

Also you can create bean programmatically and can register to the context:

GenericWebApplicationContext context = new GenericWebApplicationContext();
RootBeanDefinition anyBean = new RootBeanDefinition(AnyBean.class);
context.registerBeanDefinition("anyBean",anyBean);

Hope this will give the answer to your question. Thanks.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜