1

我试图配置弹簧缓存,但该方法仍在执行。我有以下代码,并且 CivilStatus 缓存不起作用。getCivilStatus() 方法总是被执行。有人知道原因吗?

@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;
}
}

}

4

2 回答 2

1

我相信您正在使用 spring boot 并使用类似这样的类设置服务器(如下所示)。在同一个类上添加 EnableCaching 注释并定义 CacheManager 如下所示,而不是单独的配置类。这将确保在您的类初始化之前启用缓存。

@Configuration
@EnableAutoConfiguration
@ComponentScan
@EnableCaching
@PropertySource(ignoreResourceNotFound = true, value = {"classpath:application.properties"})
@ImportResource(value = { "classpath*:spring/*.xml" })
public class MyBootServer{

public static void main(String args[]){
    ApplicationContext ctx = SpringApplication.run(MyBootServer.class, args);
}

@Bean(name="cacheManager")
public CacheManager getCacheManager() {
...// Your code
}
}

您的所有代码都没有错。我在我的 Spring Boot 示例代码中测试了您的配置,它可以工作

于 2014-12-13T14:54:39.157 回答
0

您不需要 AOP 和缓存复杂性,您的用例要简单得多。只需创建一个在启动时加载文件并让您getCivilStatus返回该地图的方法。简单了很多。

@Service
public class SocioDemographicInfoService implements ResourceLoaderAware {

    private final Map<String, String> civilStatus = new HashMap<String, String>();

    private ResourceLoader loader;

    @PostConstruct
    public void init() {
        log.info("Retrieving civilStatus");
        Map<String, String> civilStatus = new HashMap<String, String>();
        BufferedReader br = null;
        String line = "";
        String cvsSplitBy = ",";
        Resource input = loader.getResource("classpath:CatalogoEstadoCivil.csv"));
        if (input.isReadable() ) {
            File file = input.getFile();
            br = new BufferedReader(new FileReader(file));
            try {
                while ((line = br.readLine()) != null) {
                    String[] cod = line.split(cvsSplitBy);
                    civilStatus.put(cod[0].trim(), cod[1]);
                }
            } catch (IOException e) {
                logger.error("Error reading file", e_;
            } finally {
                if (br != null) {
                    try { br.close() } catch( IOException e) {}
                }               
            }   
        }   
    }

    public Map<String, String> getCivilStatus() {
        return this.civilStatus;
    }

    public void setResourceLoader(ResourceLoader loader) {
        this.loader=loader;
    }

}

像这样的东西应该工作。它在构建 bean 后加载您的(此代码可能可以通过使用 commons-io 之类的东西进行优化)。注意我使用 SpringsResourceLoader来加载文件。

于 2014-12-13T16:00:50.687 回答