我写了一个包装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有多线程控制,这样做是不是有什么问题?应该怎么处理比较好?
Your understanding is correct. It can be assembled multiple times, but the same instance is injected, so you need to handle concurrency yourself
As @chiyx said, the two
Controller
calls are the same instanceAccording to what you wrote
EhcacheWrapper
类(没有全局变量)所以按照你给出的代码来看,没有形成竞争条件,所以不会有什么并发问题,除非put
方法里面有竞争条件.从另外一方面来说,如果put
里面有竞争条件,那么其实和EhcacheWrapper
It doesn’t matter whether the class is a singleton