Spring 中初始化一個Bean物件時依賴其他Bean物件空指標異常
阿新 • • 發佈:2019-01-11
1. Bean依賴關係
一個配置類的Bean,一個例項Bean;
例項Bean初始化時需要依賴配置類的Bean;
1.1 配置類Bean
@ConfigurationProperties(prefix = "system") public class SystemConfig { private Integer type; private String rootPath; }
1.2 例項Bean
@Component public class HDFSFileHandler implements FileHandler { @Autowiredprivate SystemConfig config; private FileSystem fileSystem; public HDFSFileHandler(){ start(); } /** * 初始化 fileSystem */ private void start() { try { // 此處 config 空指標異常 if (SystemConstant.FILE_SYSTEM_HDFS.equals(config.getType())){ String uri= "hdfs://" + config.getHdfsIp() + ":" + config.getHdfsPort(); fileSystem = FileSystem.get(new URI(uri), new Configuration(), "hadoop"); log.debug("uri:" + uri); log.debug("fileSystem:" + fileSystem); } } catch (Exception e) { log.error("init fileSystem occur a exception",e); } } }
2. 問題現象
例項Bean初始化時配置類Bean空指標異常;
3. 解決方案
3.1 方案一
構造器中將Bean作為引數顯式的傳入;
@Component public class HDFSFileHandler implements FileHandler { private SystemConfig config; private FileSystem fileSystem; // 構造器顯式傳入引數 public HDFSFileHandler(SystemConfig config) { this.config = config; start(); } /** * 初始化 fileSystem */ private void start() { try { if (SystemConstant.FILE_SYSTEM_HDFS.equals(config.getType())){ String uri = "hdfs://" + config.getHdfsIp() + ":" + config.getHdfsPort(); fileSystem = FileSystem.get(new URI(uri), new Configuration(), "hadoop"); log.debug("uri:" + uri); log.debug("fileSystem:" + fileSystem); } } catch (Exception e) { log.error("init fileSystem occur a exception",e); } } }
3.2 @Autowired + @PostConstruct
@Component public class HDFSFileHandler implements FileHandler { @Autowired private SystemConfig config; private FileSystem fileSystem; public HDFSFileHandler() { start(); } /** * 初始化 fileSystem */ @PostConstruct private void start() { try { if (SystemConstant.FILE_SYSTEM_HDFS.equals(config.getType())){ String uri = "hdfs://" + config.getHdfsIp() + ":" + config.getHdfsPort(); fileSystem = FileSystem.get(new URI(uri), new Configuration(), "hadoop"); log.debug("uri:" + uri); log.debug("fileSystem:" + fileSystem); } } catch (Exception e) { log.error("init fileSystem occur a exception",e); } } }