如何从静态内部类构造函数创建 Spring bean?

发布于 2024-09-25 11:36:04 字数 745 浏览 0 评论 0原文

我正在尝试使用 Spring Framework IoC 容器来创建类的实例 ThreadPoolExecutor.CallerRunsPolicy。在 Java 中,我会这样做......

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

但是当我尝试在 Spring 中执行相同的操作时,它会抛出 CannotLoadBeanClassException

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

更一般地说:在 Spring ApplicationContext XML 中,如何调用静态内部类的构造函数?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

A君 2024-10-02 11:36:04

我认为它不起作用的原因是 Spring 无法将其理解为静态内部类。
也许这可以工作:

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

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>
々眼睛长脚气 2024-10-02 11:36:04

使用 工厂方法属性

以下 bean 定义指定将通过调用工厂方法来创建 bean。定义没有指定返回对象的类型(类),只指定包含工厂方法的类。在此示例中,createInstance() 方法必须是静态方法。


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"/>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文