简体   繁体   English

关于弹簧容器急切的单例设计模式

[英]Regarding spring container eagerly singleton design pattern

I have developed an utility class for spring which is a singleton which will provide the reference of container for the whole application , below is my class.. 我已经为spring开发了一个实用程序类,它是一个单例,它将为整个应用程序提供容器的引用,下面是我的类。

public class SpringUtility 
{
    private static BeanFactory factory ;
    static
    {try
        {BeanFactory factory = new XmlBeanFactory(new FileSystemResource("Spring.xml"));
        }   catch(Exception e) 
        {
            e.printStackTrace();
        }
    }

    private SpringUtility() 
    {}

    public static BeanFactory getBeanFactory()
    {       return factory;
    }}

Now please advise I want to convert it into style of eager singleton, Please advise how this could be achieved. 现在,请告知我要将其转换为渴望的单例样式,请告知如何实现。 please advise how this same class could be converted it in eager singleton design pattern such as the normal eager design pattern is .. 请告知如何将同一类转换为渴望的单例设计模式,例如正常的渴望设计模式为..

public class SingletonEager {

    private final static SingletonEager INSTANCE = new SingletonEager();

    private SingletonEager() {
    }

    public static SingletonEager getInstance() {
        return SingletonEager.INSTANCE;
    }

    protected Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
    }
}

similar way I want for spring one too please advise 我也想以类似的方式来春季

If you want BeanFactory to grab beans from Spring context, then I'd suggest you to implement BeanFactoryAware , It would stay singleton & eagerly loaded 如果您希望BeanFactory从Spring上下文中获取Bean,那么我建议您实现BeanFactoryAware ,它将保持单例状态并热切加载

public class BeanManager implements BeanFactoryAware {

  private BeanFactory beanFactory;

  public Person getPerson(){ beanFactory.getBean(Person.class) ;}   

}

And mark this BeanManager class as spring bean 并将此BeanManager类标记为spring bean

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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