简体   繁体   中英

final Util Class Static vs Singleton Class

Currently I'm trying to Implement a utility Class that generates an invoice in a PDF Format and I predict that I'll need spring beans to be injected in my Utility Class Afterwards.

But I don't need the class to be instanciated, I only need the methods. So for me it's a dilemma

So I did some research and I still haven't made my mind If I want a spring singleton bean or .

Spring Singleton : Source

@Service
public class Singleton {

private static AtomicReference<Singleton> INSTANCE = new AtomicReference<Singleton>();

public Singleton() {
    final Singleton previous = INSTANCE.getAndSet(this);
    if(previous != null)
        throw new IllegalStateException("Second singleton " + this + " created after " + previous);
}

public static Singleton getInstance() {
    return INSTANCE.get();
}
}

Or A final Class :

 public final InvoiceUtil {

  private InvoiceUtil() {} 

  public static String convertToPDF (Template template) {
    //Do the work
  }

 }

but with the second approach, my class isn't managed by Spring so I can not inject beans to it.

Make me undrestand !! :p

If you use a Spring bean, do not implement Spring Service as a Singleton with getInstance(). Just add @Service and Spring will only instantiate it once.

You can use static methods, and later pass any dependency also to these methods (if those are few dependencies):

public static String convertToPDF (Template template, NeededHelper helper) {
     ...
}

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