首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >BeanCurrentlyInCreationException for actionPerformed(AWT)

BeanCurrentlyInCreationException for actionPerformed(AWT)
EN

Stack Overflow用户
提问于 2017-04-02 01:47:08
回答 3查看 1.3K关注 0票数 6

创建一个新按钮,我必须在一个新线程中运行代码。

通常我们使用new Thread(....).start();,但我想知道为什么不能使用@Async-Annotation。

这是“守则”:

代码语言:javascript
复制
package net.vectorpublish.desktop.vp;

import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;
import javax.swing.ImageIcon;
import javax.swing.SwingUtilities;

import org.springframework.scheduling.annotation.Async;

import net.vectorpublish.desktop.vp.api.history.Redo;
import net.vectorpublish.desktop.vp.api.layer.Layer;
import net.vectorpublish.desktop.vp.api.ui.Dialog;
import net.vectorpublish.desktop.vp.api.ui.KeyframeSlider;
import net.vectorpublish.desktop.vp.api.ui.ToolBar;
import net.vectorpublish.desktop.vp.api.ui.VPAbstractAction;
import net.vectorpublish.desktop.vp.api.vpd.DocumentNode;
import net.vectorpublish.desktop.vp.api.vpd.VectorPublishNode;
import net.vectorpublish.desktop.vp.gantt.AddTaskData;
import net.vectorpublish.desktop.vp.gantt.AddTaskHistoryStep;
import net.vectorpublish.desktop.vp.gantt.Priority;
import net.vectorpublish.desktop.vp.utils.SetUtils;
import net.vectorpublish.destkop.vp.gantt.rule.VetoableTaskAdder;

@SuppressWarnings("restriction")
@Named
public class AddTask extends VPAbstractAction implements NodeSelectionChangeListener {

    public AddTask() {
        super(GanttText.ADD_TASK, GanttText.ADD_TASK_TT, false);
    }

    @Inject
    private final Dialog dlg = null;

    @Inject
    private final History hist = null;

    @Inject
    private final Redo redo = null;

    @Inject
    private final Layer layer = null;

    @Inject
    private final ToolBar toolbar = null;

    @Inject
    private final KeyframeSlider slider = null;

    @Inject
    private final Set<VetoableTaskAdder> council = null;

    private DocumentNode doc;

    @Async // <----------------------------------------------- This creates the Exception!
    public void actionPerformed(ActionEvent arg0) {
        try {
            VectorPublishNode selected = layer.getSelection().iterator().next();
            Future<String> taskId = dlg.ask(GanttText.NAMESPACE, "ID", "");
            Future<String> info = dlg.ask(GanttText.NAMESPACE, "Detail", "");
            Future<Priority> prio = dlg.ask(GanttText.NAMESPACE, "Name", Priority.values());
            Future<Float> points = dlg.ask(GanttText.NAMESPACE, "Storypoints", 3f);
            Future<String> username = dlg.ask(GanttText.NAMESPACE, "User", "");
            Future<String> avatar = dlg.ask(GanttText.NAMESPACE, "Avatar-Image", "www.test.com/User.png");
            AddTaskData addTaskData = new AddTaskData(taskId.get(), info.get(), prio.get(),
                    SetUtils.nodeToImmutableIndex(selected), slider.getTime(), points.get(), username.get(),
                    load(avatar.get()));
            AddTaskHistoryStep data = new AddTaskHistoryStep(hist, addTaskData);
            redo.actionPerformed(arg0);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    private BufferedImage load(String string) throws MalformedURLException {
        ImageIcon ii = new ImageIcon(new URL(string));
        return (BufferedImage) ii.getImage();
    }

    public void changedNodeSelection() {
        Set<VectorPublishNode> nodes = layer.getSelection();
        if (nodes.size() != 1) {
            setEnabled(false);
        } else {
            boolean veto = false;
            for (VetoableTaskAdder vetoableTaskAdder : council) {
                veto &= vetoableTaskAdder.hasVeto(nodes);
            }
            setEnabled(!veto);
        }
    }

    @PostConstruct
    public void setup() {
        toolbar.add(this);
    }
}

这是一个例外:

代码语言:javascript
复制
DefaultI8nImageFactory Found: Image for key net.vectorpublish:io/new/large in cache!     (DefaultI8nImageFactory > NewFile)
DefaultI8nImageFactory Found: Image for key net.vectorpublish:io/open/small in cache!    (DefaultI8nImageFactory > OpenImpl)
DefaultI8nImageFactory Found: Image for key net.vectorpublish:io/open/large in cache!    (DefaultI8nImageFactory > OpenImpl)
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'addTask': Bean with name 'addTask' has been injected into other beans [nodeSelectionChangeImpl,translation] in its raw version as part of a circular reference, but has eventually been wrapped. This means that said other beans do not use the final version of the bean. This is often the result of over-eager type matching - consider using 'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.
org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'addTask': Bean with name 'addTask' has been injected into other beans [nodeSelectionChangeImpl,translation] in its raw version as part of a circular reference, but has eventually been wrapped. This means that said other beans do not use the final version of the bean. This is often the result of over-eager type matching - consider using 'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:583)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:754)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
    at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:84)
    at net.vectorpublish.desktop.vp.VectorPublishApplicationContext.<init>(VectorPublishApplicationContext.java:18)
    at net.vectorpublish.desktop.vp.Startup.main(Startup.java:30)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:282)
    at java.lang.Thread.run(Thread.java:745)

编辑

由于一些更高的决定,我必须尊重:

  1. 我必须有字段final
  2. 不能自动使用构造函数。
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-04-09 10:57:49

一个VPAbstractAction是自动的,渴望总是和循环。你不能异步一个急切的bean。

票数 2
EN

Stack Overflow用户

发布于 2017-04-04 10:15:12

在本例中,BeanCurrentlyInCreationException的根本原因是在final字段上使用了@Inject (或其对应的@Autowired)。

为了理解这种行为,应该考虑bean的生命周期。

  • Spring首先使用其默认值(即null )的字段构造对象。
  • Post构造对象Spring使用反射注入,即初始化字段的实际值

因此,第二步与字段上的final声明相矛盾,该字段规定该字段可以有一个且只有一个值,应该在构造时分配该值。

因此,要解决这个问题,要么从字段中删除final声明,要么使用构造函数注入(在这种特殊情况下,考虑到依赖项的数量,前者是可取的)。

如果需要更多的信息,请在评论中告知。

希望这能有所帮助!

P.S.:虽然在任何正式文档中都没有明确提到这种行为,但是这里对此进行了微妙的解释,例如,只有在构造函数注入的情况下,字段才被标记为final

编辑 :-

引入@Async强制Spring来创建和使用豆类代理,如果存在循环引用,这将导致BeanCurrentlyInCreationException

这是因为Spring最初注入原始版本的bean,并尝试向其应用方面,但由于默认情况下禁用了RawInjectionDespiteWrapping,所以失败了,尼古拉斯拉布罗指出了这一点。

要克服这一点

  • 打破循环引用(虽然建议,但需要重新设计,因此需要大量的努力)
  • 使用延迟初始化(如下所述)

延迟Bean初始化

如果使用xml配置,则在根元素中提供如下所示的default-lazy-init="true"

代码语言:javascript
复制
<beans default-lazy-init="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns="http://www.springframework.org/schema/beans"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context.xsd">
   <!-- Other configuration(s) -->
</beans>

对于Java配置,请在下面使用

代码语言:javascript
复制
@Configuration
@Lazy // For all Beans to load lazily (equivalent to default-lazy-init="true")
public class SomeConfig {

    @Bean
    // @Lazy - Only if particular bean should load lazily
    public SomeBean someBean() {
        return new SomeBean();
    }
}

此外,如果使用组件扫描(通过@Inject或xml配置),请确保标记为@Lazy的字段应与@Lazy一起使用,例如请参阅下面

代码语言:javascript
复制
 @Inject
 @Lazy
 private Dialog dlg;
票数 4
EN

Stack Overflow用户

发布于 2017-04-04 14:38:32

如果查看抛出异常(org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean)的代码,则会引发异常,因为有循环引用和代理,而配置不允许RawInjectionDespiteWrapping

似乎有一个循环引用根据您的例外。我将在循环的另一端将Foo称为AddTask <=> Foo

  • Spring初始化FooFoo需要AddTask 的一个实例
    • Spring首先实例化AddTask并注入到Foo中。

  • 然后初始化AddTask,它已经被Foo实例化(并注入)。因为有了@Async注释,所以必须对其进行代理。因此,注入到Foo实例的实例将不同于代理实例。

这导致了例外。修复循环引用,它应该修复异常。作为一个良好的实践,我建议不允许循环引用.

注意:在我看来,final字段是不必要的,容易出错,并且会妨碍单元测试/模拟。如果您删除或保留它,但使用构造函数注入,可能会更好。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43163805

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档