简体   繁体   English

Spring 与 class.forname()

[英]Spring with class.forname()

If an application is managed by the Spring container, can a developer still use class.forName() to create an instance of a particular class?如果应用程序由 Spring 容器管理,开发人员是否仍可以使用class.forName()创建特定 class 的实例? Or will that violate the Spring container and result in some exception?还是会违反 Spring 容器并导致一些异常?

Yes you can use it.是的,你可以使用它。 The resulting object will not be managed by Spring, however.但是,生成的 object 不会由 Spring 管理。

If you are developing a web-application and assuming you have beans defined in applicationContext.xml then you can use:如果您正在开发 Web 应用程序并假设您在applicationContext.xml中定义了 bean,那么您可以使用:

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

where anyBean is the id of the bean defined in that xml.其中anyBean是在 xml 中定义的 bean 的 id。 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:您还可以以编程方式创建 bean 并可以注册到上下文:

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

Hope this will give the answer to your question.希望这将为您的问题提供答案。 Thanks.谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM