3

When I try to use the Resource annotation in a servlet, Sonar triggers rule squid:S2226 "Servlets should not have mutable instance fields" and tells me make the variable final or static.

But resource injection does not work and final and static variables.

Is it a bug in sonar or resource injection is not recommended anymore in servlets ?

public class MyServlet extends HttpServlet {
    @Resource(name = "jdbc/database")
    private DataSource dataSource;
}

A similar conundrum appears with ServletConfig

private ServletConfig config;

@Override
public void init(ServletConfig config) throws ServletException {
    this.config = config;
}

Here, config cannot be made final, but making it static trigger the other rule squid:S2696 : "Instance methods should not write to "static" fields"

I meet this situation with SonarLint for Eclipse 3.3.1.201712071600, if that is useful.

G. Ann - SonarSource Team
  • 22,346
  • 4
  • 40
  • 76
Gzorg
  • 809
  • 4
  • 10
  • 25

1 Answers1

1

Injected Members

You are right about injected Members (@EJB, @Resource, ...) and there are (now fixed) Issues in the SONARJAVA Issue Tracker.

For example SONARJAVA-2744
Title: "S2226 should not raise issues for field annotated with @Resource"
Solved with Version 5.4 of the Security Rules

Members initialized in #init

There is another (solved) issue: SONARJAVA-1458
Members initialized in #init should not trigger squid:S2226.

According ServletConfig:
Usually there is no need to hold a reference to ServletConfig because it is accessible using GenericServlet#getServletConfig.

DaniEll
  • 1,022
  • 4
  • 22
  • 31