首先我說一下我遇到的問題,再項目初始化時候,spring容器初始化前要執行的操作中使用到了bean去做一些增刪改查操作,這樣做是不能自己使用springbean的數據源去操作的,所以需要動態獲取springbean,又不想重新封裝jdbc數據源去操作,,可以直接獲取到spring配置文件中的數據源進行操作
第一種方法是
在初始化時保存ApplicationContext對象
代碼:
ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");
ac.getBean("beanId");
說明:這種方式適用於采用Spring框架的獨立應用程序,需要程序通過配置文件手工初始化Spring的情況。
//但是我不明白怎么去配置初始化spring,我寫的時候 new FileSystemXmlApplicationContext("applicationContext.xml");返回的不是ApplicationContext,所以pass掉了,,還需要再學習一下
鬼使神差的又可以了,,, ApplicationContext ac = new FileSystemXmlApplicationContext("app-persistence.xml");可以拿到了哦各位
方法二:通過Spring提供的工具類獲取ApplicationContext對象
代碼:
import org.springframework.web.context.support.WebApplicationContextUtils;
ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc);
ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc);
ac1.getBean("beanId");
ac2.getBean("beanId");
說明:
這種方式適合於采用Spring框架的B/S系統,通過ServletContext對象獲取ApplicationContext對象,然后在通過它獲取需要的類實例。
上面兩個工具方式的區別是,前者在獲取失敗時拋出異常,后者返回null。
方法三:繼承自抽象類ApplicationObjectSupport
說明:抽象類ApplicationObjectSupport提供getApplicationContext()方法,可以方便的獲取到ApplicationContext。
Spring初始化時,會通過該抽象類的setApplicationContext(ApplicationContext context)方法將ApplicationContext 對象注入。
方法四:繼承自抽象類WebApplicationObjectSupport
說明:類似上面方法,調用getWebApplicationContext()獲取WebApplicationContext
方法五:實現接口ApplicationContextAware
說明:實現該接口的setApplicationContext(ApplicationContext context)方法,並保存ApplicationContext 對象。
Spring初始化時,會通過該方法將ApplicationContext對象注入。
最后說一下我所使用的是第五種方式,該方法實現ApplicationContextAware接口,然后直接通過上下文就可以獲取配置文件中的bean,
注意:該方法不以來servlet,不需要注入的方式,在服務器啟動時,Spring容器初始化時,不能通過以下方法獲取Spring 容器。
WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
wac.getBean("");
直接上代碼
@Service
public class BlhRequestExecutor
extends AbstractRequestExecutor implements ApplicationContextAware
{
private Logger logger = LoggerFactory.getLogger(BlhRequestExecutor.class);
private static ApplicationContext context = null;
public BlhRequestExecutor() {}
public IZrarResponse service(HttpServletRequest request, HttpServletResponse response) throws BaseException {
IZrarRequest zrarRequest = new ZrarRequest(request);
IBaseZrarDao dao = (IBaseZrarDao) context.getBean("dao");
//記錄日志實體
System.out.println("----------------------------------記錄日志開始---------------");
String id = IdGenerator.getGuid();
String commite =null;
String endTime =null;
String usedTime =null;
long end;
long start;
//獲取系統時間
String startTime = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(new Date());
start = System.currentTimeMillis();
//獲取登陸用戶賬戶
String userId = LoginCtrlSession.getYhid();
System.out.println(userId);
String userName = LoginCtrlSession.getYhmc();
String visitUrl = String.valueOf(request.getRequestURL().toString());
System.out.println("----------------------------------記錄日志中---------------");
try {
String[] reqInfo = UrlParser.parseReqGoal(request);
Object visitClass = EasywebContext.Factory.getInstance().getBeanWithBlhAnnotation(reqInfo[0]);
if (visitClass == null) { throw new BaseException(1002);
}
if (this.logger.isDebugEnabled()) {
this.logger.debug("|>> Start " + Thread.currentThread().getId() + " " + reqInfo[0] + "_" + reqInfo[1]);
}
Method visitMethod = visitClass.getClass().getMethod(reqInfo[1], new Class[] { IZrarRequest.class });
IZrarResponse rs = (IZrarResponse)visitMethod.invoke(visitClass, new Object[] { zrarRequest });
String error = rs.getError();
if (StringUtil.isNotNull(error)) {
throw new BusinessException(rs.getErrorCode(), error);
}
end = System.currentTimeMillis();
endTime = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(new Date());
usedTime =String.valueOf((end-start)/1000).toString();
System.out.println("------aop執行時間-----------"+(end-start));
commite = "執行成功";
System.out.println("----------------------------------記錄日志結束---------------");
dao.execute("insert into aoploginfo set id='"+id+"', startTime='"+startTime+"',endTime='"+endTime+"',usedTime='"+usedTime+"', visitUrl='"+visitUrl+"',userId='"+userId+"',userName='"+userName+"',commite='"+commite+"'");
return rs;
} catch (SecurityException e) {
commite = "執行異常";
throw new BaseException("SecurityException", e);
} catch (IllegalArgumentException e) {
commite = "執行異常";
throw new BaseException("IllegalArgumentException", e);
} catch (NoSuchMethodException e) {
commite = "執行異常";
throw new BaseException(1002);
} catch (IllegalAccessException e) {
commite = "執行異常";
throw new BaseException(1003, e);
} catch (InvocationTargetException e) {
commite = "執行異常";
Throwable targetException = e.getTargetException();
if (BaseException.class.isAssignableFrom(targetException.getClass())) {
throw ((BaseException)targetException);
}
throw new BaseException(targetException);
} catch (BaseException e) {
commite = "執行異常";
throw e;
} finally{
if("執行異常".equals(commite)){
end = System.currentTimeMillis();
endTime = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(new Date());
usedTime =String.valueOf((end-start)/1000).toString();
dao.execute("insert into aoploginfo set id='"+id+"', startTime='"+startTime+"',endTime='"+endTime+"',usedTime='"+usedTime+"', visitUrl='"+visitUrl+"',userId='"+userId+"',userName='"+userName+"',commite='"+commite+"'");
}
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
context = applicationContext;
}
public static Object getBean(String name){
return context.getBean(name);
}
}
