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?
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<>();
}
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);
....
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With