获取springbean的几种方式
首先我说一下我遇到的问题,再项目初始化时候,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("");
直接上代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | @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); } } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步