直接new 一個serviceB是不行的
獲得applicationContext就可以了
AppContext
public class AppContext {
private static ApplicationContext applicationContext;
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static void setApplicationContext(
ApplicationContext applicationContext) {
AppContext
}
}
SpringService
public class SpringBeanService {
private static SpringBeanService instance;
private ApplicationContext applicationContext;
public static synchronized SpringBeanService getInstance() {
if (instance == null) {
instance = new SpringBeanService();
}
return instance;
}
public ApplicationContext getApplicationContext() {
return this
}
public void setApplicationContext(ApplicationContext applicationContext) {
this
}
public UserService getUserService(){
return (UserService)AppContext
}
}
ApplicationContext的初始化
public class ConfigLoadListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent contextEvent) {
try {
WebApplicationContext context =WebApplicationContextUtils
AppContext
//讀配置
try {
ServletContext context
String path=context
InputStream in =context
Properties properties = new Properties();
properties
GlobalConstant
in
} catch (IOException e) {
e
}
} catch (HibernateException e) {
System
System
}
}
public void contextDestroyed(ServletContextEvent contextEvent) {
}
}
From:http://tw.wingwit.com/Article/program/Java/ky/201311/28919.html