我正在尝试在mapStore 内自动装配jdbc 模板..但我遇到了空指针异常。
我研究了很多例子,但仍然无法解决这个问题。
这是我的主要课程
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class TestCacheApplication {
public static void main(String[] args) {
SpringApplication.run(TestCacheApplication.class, args);
System.err.println("......running successfully......");
}
}
这是我的缓存配置代码
@Component
public class CacheConfig {
@Bean
public static Config config() {
System.err.println("config class");
Config config = new Config();
config.setInstanceName("hazelcast");
MapConfig mapCfg = new MapConfig();
mapCfg.setName("first-map");
mapCfg.setBackupCount(2);
mapCfg.setTimeToLiveSeconds(300);
MapStoreConfig mapStoreCfg = new MapStoreConfig();
mapStoreCfg.setClassName(DataMapStore .class.getName()).setEnabled(true);
mapCfg.setMapStoreConfig(mapStoreCfg);
config.addMapConfig(mapCfg);
return config;
}
}
和 TblRepo 实施
@Service
public class DataTblRepoImpl implements DataTblRepo {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void save(String id, String name) {
Object[] params = new Object[] { id, name };
int[] types = new int[] { Types.VARCHAR, Types.VARCHAR };
String insertSql = "INSERT INTO public.person(id, name) VALUES(?, ?)";
jdbcTemplate.update(insertSql, params, types);
}
和我注释过的 TblRepo 接口@存储库注解..
和我的地图存储类
@SpringAware
public class DataMapStore implements MapStore<String, ModelClass>{
@Autowired
DataTblRepo dataTblRepo;
@Override
public void store(String key, ModelClass value) {
dataTblRepo.save(value.getId(), value.getName());
}
//remaining methods will come here
}
和控制器
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/api/v1")
public class DataController {
@Autowired
DataService dataService;
HazelcastInstance hazelCast = Hazelcast.getHazelcastInstanceByName("hazelcast");
@PostMapping("/{test}")
public String saveDatafrom(@RequestBody ModelClass model) {
hazelCast.getMap("first-map").put(model.getId(), model);
return "stored";
}
}
这是程序流程。当我启动应用程序时,第一个 Cacheconfig 类将运行。
- 在控制器中,当我执行 map.put() 操作时,数据将转到 DataMapStore 类并调用 store 方法将数据保存在数据库中..因为 DataTblRepo 为 null,因此 store 方法本身的操作失败..*我也尝试在 DataMapStore 类上添加 @component
但就我而言,我收到此错误
- "message": "无法调用 "com.example.demo.repo.DataTblRepository.save(String, String)",因为 "this.dataTableRepo" 为 null",
-
我在许多平台上也看到了同样的问题,但仍然无法解决这个问题。
任何建议都会非常有帮助