我想在Spring应用程序的上下文中实现Singleton模式。 所以即使我的单身物体将在春天创建。一个用Spring实现Singleton模式的好方法
为了做到这一点:
我把实现了ApplicationContextAware获得从Spring上下文豆类:
public class AppContext implements ApplicationContextAware
{
/**
* Private instance of the AppContext.
*/
private static AppContext _instance;
/**
* @return the instance of AppContext
*/
public static AppContext getInstance()
{
return AppContext._instance;
}
/**
* Instance of the ApplicationContext.
*/
private ApplicationContext _applicationContext;
/**
* Constructor (should never be call from the code).
*/
public AppContext()
{
if (AppContext._instance != null)
{
throw (new java.lang.RuntimeException(Messages.getString("AppContext.singleton_already_exists_msg"))); //$NON-NLS-1$
}
AppContext._instance = this;
}
/**
* Get an instance of a class define in the ApplicationContext.
*
* @param name_p
* the Bean's identifier in the ApplicationContext
* @param <T>
* the type of the returned bean
* @return An instance of the class
*/
@SuppressWarnings("unchecked")
public <T> T getBean(String name_p)
{
return (T) _applicationContext.getBean(name_p);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext_p) throws BeansException
{
_applicationContext = applicationContext_p;
}
}
我的单例类:
public class MySingleton {
private static MySingleton instance= null;
public static final String BEAN_ID = "mySingletonInstanceId";
private MySingleton(){}
public static MySingleton getInstance(){
return AppContext.getInstance().getBean(mySingletonInstanceId.BEAN_ID);
}
}
我的application.xml file:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
xmlns:cxf="http://cxf.apache.org/core" xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
http://cxf.apache.org/jaxrs
http://cxf.apache.org/schemas/jaxrs.xsd
http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd">
<!--some code-->
<bean id="idAppContext" class="com.AppContext" />
<bean id="mySingletonInstanceId" class="com.MySingleton"/>
<!--some code-->
</beans>
你认为我的代码好吗?
实例字段不再需要?
考虑到Spring会管理每一件事情,getInstance()只能返回由spring创建的单例实例吗?
不要编写这样做的代码。使用依赖注入来代替这个丑陋的装置。 –
默认情况下,spring bean是单身人士。尝试只使用依赖注入和春天会为你做。 –
如果我很好理解,在Spring应用程序中不再需要使用单例模式? –