Search code examples
javaspringsonarqube

Spring App SonarQube Issue S3749


I am running into an issue with my Spring Applications and SonarQube. SQ is flagging both examples with "Annotate this member with "@Autowired", "@Resource", "@Inject", or "@Value", or remove it." on the instance variable mapLoadedByDatabaseCalls

Example 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);
        ....
    }
}

Example 2:

@Service
public class Service {

    @Autowired
    private Dao dao;

    private Map<Object, Object> mapLoadedByDatabaseCalls;

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

What is the correct way to instantiate variables after DI has completed?


Solution

  • I believe that this is kludgy and that your original code is better, but this will eliminate the SonarQube complaint. Initialize your map in a @Bean, then reference that as @Autowired. Load the map with data in the @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);
        ....
    }