Search code examples
spring-bootautowiredspotbugs

How to ignore EI_EXPOSE_REP2 in case of spring autowired components


In my Spring Boot application, I use com.github.spotbugs:spotbugs-maven-plugin plugin. The spotbugs check reports no issues on following class:

@Service
public class FooService {
    @Autowired
    CocoComponent cocoComponent;

    @PostConstruct
    public void init() {
        System.out.println(cocoComponent.getGreeting() + " world!");
    }
}

This works fine. However, since the autowired fields are not meant to be mutated after injection, I would prefer declaring them final. Like this:

@Service
public class BarService {
    final CocoComponent cocoComponent;

    public BarService(CocoComponent cocoComponent) {
        this.cocoComponent = cocoComponent;
    }

    @PostConstruct
    public void init() {
        System.out.println(cocoComponent.getGreeting() + " world!");
    }
}

The problem is, spotbugs check reports issue on BarService class:

[ERROR] Medium: new xxx.nnn.BarService(CocoComponent) may expose internal representation by storing an externally mutable object into BarService.cocoComponent [xxx.nnn.BarService] At BarService.java:[line 14] EI_EXPOSE_REP2

Of course I can:

  • keep using @Autowired non-final fields like in FooService
  • annotate all autowired constructors with @SuppressFBWarnings("EI_EXPOSE_REP2")

But, IMHO, neither is ideal.

My main question: Is there a way to configure spotbugs to not raise EI_EXPOSE_REP2 due storing objects of @Component (and any derivates such as @Service, @Repository, ..) annotated class in another object?

Alternatively (but not as ideal): Is there a way to configure spotbugs to not raise EI_EXPOSE_REP2 due storing mutable objects on an instance of @Component (and any derivates such as @Service, @Repository, ..) annotated class via constructor? I guess I could use a filter file but, AFAIK, there's no filter matching for annotations, so it would be based on package or class name pattern which is not pretty.

Any other suggestions to avoid polluting the code with @SuppressFBWarnings?


Solution

  • Using the information in the URL below as a hint, I was able to suppress the EI_EXPOSE_REP2 warning that occurs during constructor injection. (Might be a bit crude solution)

    How to exclude a constructor in findbugs?

    https://spotbugs.readthedocs.io/ja/latest/filter.html

    spotbugs filter setting file

    <FindBugsFilter ...>
    
        ...
        ...
        <Match>
            <Method name="&lt;init&gt;"/>
            <Bug pattern="EI_EXPOSE_REP2" />
    
        </Match>
        ...
        ...
    
    </FindBugsFilter>