我試圖配置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