I have a spring-boot project that contains a BookMapper bean:
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface BookMapper {
// some CRUD methods here...
}
The bean is created by mybatis, and it's a Singleton. Usually, I use the bean with @Autowired:
@Service
public BookService {
@Autowired
private BookMapper bookMapper;
}
I also have a file like this:
@Component
public class BeanUtil implements ApplicationContextAware {
private static ApplicationContext ac;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ac = applicationContext;
}
public static <T> T getBean(Class<T> clazz){
return ac.getBean(clazz);
}
public static <T> T getBean(String name, Class<T> clazz){
return ac.getBean(name, clazz);
}
}
Sometimes I just fetch the bean using the BeanUtil class:
BookMapper bookMapper = BeanUtil.getBean(BookMapper.class);
That is convenient because I can get a bean from a static method.
Now the problem is, when I run integration tests, I find that BookMapper fetched using the above two ways (@Autowired and BeanUtil) are sometimes different (and they are sometimes the same, I cannot reproduce the problem). Why? It shouldn't happen because BookMapper is a Singleton. Is there a possible reason for it?