How to create a Spring bean from a static inner class constructor?

百般思念 提交于 2020-01-03 08:55:10

问题


I am trying to use the Spring Framework IoC Container to create an instance of class ThreadPoolExecutor.CallerRunsPolicy. In Java, I'd do it this way...

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
...
RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy();

But when I try to do the equivalent in Spring, it throws a CannotLoadBeanClassException.

<beans>
   <bean class="java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy"/>
</beans>

More generally: in a Spring ApplicationContext XML, how can you call a constructor of a static inner class?


回答1:


I think the reason it is not working is because Spring is not able to understand it as a static inner class. Probably this can work:

<beans>
   <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy"/>
</beans>



回答2:


Use the factory-method attribute:

The following bean definition specifies that the bean will be created by calling a factory-method. The definition does not specify the type (class) of the returned object, only the class containing the factory method. In this example, the createInstance() method must be a static method.

<bean id="clientService" class="examples.ClientService"
  factory-method="createInstance"/>


来源:https://stackoverflow.com/questions/3818332/how-to-create-a-spring-bean-from-a-static-inner-class-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!