Skip to content

[java] UnusedPrivateMethod for methods annotated with jakarta.annotation.PostConstruct or PreDestroy #5117

@kdebski85

Description

@kdebski85

Affects PMD Version:
7.3.0

Rule:

UnusedPrivateMethod
Description:

UnusedPrivateMethod should not be reported for methods annotated with jakarta.annotation.PostConstruct or jakarta.annotation.PreDestroy since they are usually called by a container (for example Spring).

As a workaround, the annotations can be added to configuration:

    <rule ref="category/java/bestpractices.xml/UnusedPrivateMethod">
        <properties>
            <property name="ignoredAnnotations" value="java.lang.Deprecated,jakarta.annotation.PostConstruct,jakarta.annotation.PreDestroy" />
        </properties>
    </rule>

However, I think such methods should be excluded by default.

Code Sample demonstrating the issue:

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.stereotype.Component;

@Component
public class JakartaTest {

    @PostConstruct
    private void setup() {
    }

    @PreDestroy
    private void cleanup() {
    }
}

Expected outcome:

PMD reports a violation at lines 0 and 13, but that's wrong. That's a false positive.

Running PMD through: Gradle

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-positivePMD flags a piece of code that is not problematic

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions