Home  >  Q&A  >  body text

java - @Autowired可以多次装配一个被@Component修饰的类吗?

我写了一个包装Ehcache的类EhcacheWrapper,加入多线程控制,代码如下

@service
public class EhcacheWrapper{
   public Element get(String cacheName, String key){......}
   public void put(String cacheName, String key, Object value){......}
   //多线程控制,代码略
}

我在一个controller中自动装配EhcacheWrapper,比如

public class GetLabelServiceImpl{
   @Autowired
   private EhcacheWrapper ehcacheWrapper;
   //代码略
}

我在其他controller中还能@Autowired EhcacheWrapper吗?

我觉得@Component默认的scope是singleton,只有一个实例。如果在两个类中都@Autowired EhcacheWrapper,是不是两个类都调用同一个bean呢?EhcacheWrapper有多线程控制,这样做是不是有什么问题?应该怎么处理比较好?

PHP中文网PHP中文网2741 days ago357

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-04-18 09:35:24

    Your understanding is correct. It can be assembled multiple times, but the same instance is injected, so you need to handle concurrency yourself

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 09:35:24

    1. As @chiyx said, the two Controller calls are the same instance

    2. According to what you wroteEhcacheWrapper类(没有全局变量)所以按照你给出的代码来看,没有形成竞争条件,所以不会有什么并发问题,除非put方法里面有竞争条件.从另外一方面来说,如果put里面有竞争条件,那么其实和EhcacheWrapperIt doesn’t matter whether the class is a singleton

    reply
    0
  • Cancelreply