我试图配置Spring缓存,但该方法仍然执行。我有下面的代码,并且civilStatus缓存不起作用。方法getCivilStatus()始终执行。有人知道原因吗?Spring Boot缓存不起作用
@Configuration
@EnableCaching
public class ApplicationConfig {
@Autowired
private SocioDemographicInfoService socioDemographicInfo;
@Bean
public CacheManager cacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
cacheManager.setCaches(Arrays.asList(
new ConcurrentMapCache("civilStatus");
return cacheManager;
}
}
@Service
public class SocioDemographicInfoService {
@Cacheable(value="civilStatus")
public Map<String, String> getCivilStatus(){
log.info("Retrieving civilStatus");
Map<String, String> civilStatus = new HashMap<String, String>();
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("CatalogoEstadoCivil.csv").getFile());
br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
String[] cod = line.split(cvsSplitBy);
civilStatus.put(cod[0].trim(), cod[1]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return civilStatus;
}
}
}
问题在于你的配置。您将自动将您的bean与高速缓存连接到配置中。这个实例化这个bean并且不会为了缓存而进行后期处理。 – 2014-12-13 11:55:09
非常感谢你的回答。我想在开始时加载一个文件并缓存它。你知道我该怎么开发它? – nole 2014-12-13 12:07:51
为什么你需要缓存?你可以自己做,而无需启用缓存。在'@ PostConstruct'注释的'SocioDemographicInfoService'中添加一个方法,该方法加载文件并填充地图。没有必要使用弹簧缓存抽象。 – 2014-12-13 12:45:07