V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
lxy
V2EX  ›  Java

为什么不同的 bean 会装配到同一个 component ?

  •  
  •   lxy · 2018-04-12 12:36:57 +08:00 · 1303 次点击
    这是一个创建于 2203 天前的主题,其中的信息可能已经有所发展或是发生改变。

    SpringMVC。如果我想让不同的 bean 也装配不同的 component 应该怎么做? 配置大概是这样:

    <!--Listener-->
    <bean id="MyListener" class="com.example.MyListener" scope="prototype"/>
    

    简化的例子

    
    // MyListener.java
    @Aync
    public class MyListener implements ApplicationListener<MyEvent> {
        @Autowired
        private MyExecutor myExecutor;
        private String listenerId;
    
        @Override
        public void onApplicationEvent(MyEvent myEvent) {
            this.listenerId = myEvent.getId();
            this.myExecutor.setId(myEvent.getId()); // sleep 5s
            System.out.println(this.listenerId);
        }
    }
    
    // MyExecutor.java
    @Component
    public class MyExecutor {
        private String exeId;
    
        public void setId(Stirng id) {
            this.exeId = id;
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
            }
            System.out.println(this.exeId);
        }
    }
    

    如果在 5 秒内连发两个 ID 不同的 Event,那么会看到 Event 由不同的 Listener 处理,但是执行了相同的 myExecutor。

    也试过增加这个配置,不行。

    <!--Executor-->
    <bean id="MyExecutor" class="com.example.MyExecutor" scope="prototype"/>
    
    第 1 条附言  ·  2018-04-13 11:06:29 +08:00

    惊了,这么简单的问题。按如下配置即可。Listener 还要加个setMyExecutor方法。

    <!--Listener-->
    <bean id="MyListener" class="com.example.MyListener" scope="prototype">
        <property name="myExecutor" ref="MyExecutor"/>
    </bean>
    <!--Executor-->
    <bean id="MyExecutor" class="com.example.MyExecutor" scope="prototype"/>
    
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1703 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 16:44 · PVG 00:44 · LAX 09:44 · JFK 12:44
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.