2017-08-29 117 views
1

我遇到了我的Spring應用程序和SonarQube問題。 SQ將用「@Autowired」,「@Resource」,「@Inject」或「@Value」註釋此成員,或者將其刪除,從而標記兩個示例。在實例變量mapLoadedByDatabaseCalls彈簧應用程序SonarQube問題S3749

例1:

@Service 
public class Service implements InitializingBean { 

    @Autowired 
    private Dao dao; 

    private Map<Object, Object> mapLoadedByDatabaseCalls; 

    @Override 
    public void afterPropertiesSet() throws Exception { 
     mapLoadedByDatabaseCalls= new HashMap<>(Object.class); 
     .... 
    } 
} 

例2:

@Service 
public class Service { 

    @Autowired 
    private Dao dao; 

    private Map<Object, Object> mapLoadedByDatabaseCalls; 

    @PostConstruct 
    private void setMap() { 
     mapLoadedByDatabaseCalls= new HashMap<>(Object.class); 
     .... 
    } 
} 

什麼是實例變量DI完成後,正確的方法是什麼?

回答

0

我認爲,這是缺憾和你原來的代碼是更好的,但這會消除SonarQube投訴。在@Bean中初始化您的地圖,然後將其引用爲@Autowired。用@PostConstruct中的數據加載地圖。

@Bean 
public Map<Object, Object> getMapLoadedByDatabaseCalls() { 
    return new HashMap<>(Object.class); 
} 

@Autowired 
private Map<Object, Object> mapLoadedByDatabaseCalls; 

@PostConstruct 
private void setMap() { 
    ... 
    // load data into the map 
    mapLoadedByDatabaseCalls.put(key, value); 
    .... 
} 
1

Spring Documentation >Initialization callbacks section

建議您不要使用的InitializingBean接口 因爲它不必要的夫妻代碼春天。或者, 使用@PostConstruct註釋或指定POJO初始化 方法。

本質的InitializingBean預先存在於春季JSR-250support came on Spring 2.5 onwards(包括@PostConstruct註釋)之前

+1

確實推薦@PostConstruct而不是實現InitializingBean,但這不會解決SonarQube問題。 SonarQube仍然會抱怨。 –