[英]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. 当前,我正在尝试实现一个实用程序类,该实用程序类生成PDF格式的发票,并且我预计以后需要在我的实用程序类中注入弹跳豆。
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 Spring Singleton: 来源
@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. 但是使用第二种方法时,我的班级不是由Spring管理的,因此无法向其注入bean。
Make me undrestand !! 让我无法理解! :p :p
If you use a Spring bean, do not implement Spring Service as a Singleton with getInstance(). 如果您使用Spring Bean,请不要通过getInstance()将Spring Service作为Singleton实现。 Just add @Service and Spring will only instantiate it once. 只需添加@Service,Spring只会实例化一次。
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) {
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.