Search code examples
javaspringautowiredpmd

PMD exception BeanMembersShouldSerialize on Autowired fields


I get PMD exceptions like "BeanMembersShouldSerialize" on autowired fields. The only way to stop them is using either "transient" or @SuppressWarnings. My question is what would be the right way to deal with PMD and autowired fields.

@Component
public class Sample {

@Autowired
private SoapProperties soapProperties;

public void doSomething() {
    // do something
}

Sample.java:13: Found non-transient, non-static member. Please mark as transient or provide accessors.


Solution

  • I guess there are two options. Firstly, here's the documentation for the check.

    The first option is adding a supression to your rule via the properties: violationSuppressRegex, violationSuppressXPath, prefix. I havent used the Regex and XPath options, but the XPath is interesting - if you learn to write it, you can also implement completely new checks (the syntax and AST structure are a bit arcane though). For an example of how a supression looks like in your ruleset.xml, and maybe some more info see this answer.

    The second option is taking the check's java code linked there, and implement the exception for autowired there, and then reference your class in the ruleset, while disabling the original BeanMembersShouldSerialize check. I think this would be harder, and more likely to require maintenance down the line.