2

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

类似的方式我也想要春天一个请指教

4

1 回答 1

1

如果您想BeanFactory从 Spring 上下文中获取 bean,那么我建议您实现BeanFactoryAware,它将保持单例并热切加载

public class BeanManager implements BeanFactoryAware {

  private BeanFactory beanFactory;

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

}

并将这个类标记BeanManager为spring bean

于 2012-07-02T09:33:36.967 回答