Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 823
loutambo Avatar asked Aug 29 '17 12:08

loutambo


2 Answers

A more generic solution to this that does not involve any additional annotations, is to initialize the offending variable in the class constructor.

public Service() {
  mapLoadedByDatabaseCalls = new HashMap<>();
}
like image 56
John Reece Avatar answered Oct 18 '22 05:10

John Reece


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);
    ....
}
like image 2
Paul Croarkin Avatar answered Oct 18 '22 06:10

Paul Croarkin