我已经为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();
}
}
类似的方法我也想要 Spring 的,请指教
最佳答案
如果你想让 BeanFactory
从 Spring 上下文中获取 beans,那么我建议你实现 BeanFactoryAware
, 它将保持单例并急切加载
public class BeanManager implements BeanFactoryAware {
private BeanFactory beanFactory;
public Person getPerson(){ beanFactory.getBean(Person.class) ;}
}
并将这个BeanManager
类标记为spring bean
关于java - 关于spring容器热切单例设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11291029/