问题
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