lundi 9 septembre 2019

How to avoid SonarLint UnusedPrivateMethod when instantiating Spring components?

In a basic Spring Boot app I have this component:

@Component
public class TheComponent {
    public String getKey() {return "value";}
}

used by a service. If I design my service like this:

@Service
public class TheService { 

    @Autowired
    private TheComponent theComponent;

    private final String keyValue = theComponent.getKey();

    private TheService() {}
}

then Spring Boot doesn't build because theComponent triggers a NullPointerException.

If I design it like this:

@Service
public class TheService {

    private String keyValue;

    private TheService(TheComponent theComponent) {
        keyValue = theComponent.getKey();
    }
}

then SonarLint tells me that I should Remove this unused private "TheService" constructor.

Is there a solution that would suit both Spring and SonarLint, using a private constructor ?





Aucun commentaire:

Enregistrer un commentaire