关于弹簧容器热切单身设计模式

时间:2012-07-02 09:29:49

标签: java spring design-patterns

我已经为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;
    }}

现在请建议我想将它转换成渴望单身的风格,请告知如何实现这一目标。请告知如何在急切的单一设计模式中将同一类转换为正常的热切设计模式。

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();
    }
}

我想要春天的方式也一样,请指教

1 个答案:

答案 0 :(得分:1)

如果你想让BeanFactory从Spring上下文中抓取bean,那么我建议你实现BeanFactoryAware,它会保持单身和急切地加载

public class BeanManager implements BeanFactoryAware {

  private BeanFactory beanFactory;

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

}

将此BeanManager类标记为spring bean