简体   繁体   中英

@Singleton class do I have to make constructor private

I'm writing a Singleton class in Java EE 6 using the @Singleton annotation. I have not declared a constructor.

Do I have to create a private constructor explicitly?

The reason I'm asking is that I'm using PMD and the rule UseSingleton is flagged. I think that PMD does not understand the annotation @Singleton?

PMD is recommending making the constructor private so that others may not instantiate your singleton object. It's unaware of Java EE 6 annotations.

You can safely ignore this warning.

No. Just add @Singleton on the bean class.

@Singleton
public class TesterBean {
  private int testCount = 0;
    public int getCount() {
      return testCount++;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM