方法一:(获取当前的spring容器,任何java类中适用)
ServletContext application = ServletActionContext.getServletContext();
ApplicationContext act = ContextLoader.getCurrentWebApplicationContext();UserService userService = (UserService) act.getBean("userService");
方法二:(重新加载spring容器)
ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");
方法三:(通过request或session加载spring容器)
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
<bean id="redisClient" class="com.dianping.squirrel.client.impl.redis.spring.RedisClientBeanFactory"> <!-- 集群名称,必填 --> <property name="clusterName" value="redis-hawkeye"></property> <!--读写的超时时间,缓存业务建议改成100,存储业务建议改成1000,默认值为1000。选填--> <property name="readTimeout" value="00"></property> <!--路由策略,默认值是master-only表示只从主节点读取。slave-only表示只读从节点,master-slave表示主从都可以读。选填--> <property name="routerType" value="master-only"></property> <!--连接redis节点的连接池配置--> <property name="poolMaxIdle" value="16"></property> <property name="poolMaxTotal" value="32"></property> <property name="poolWaitMillis" value="500"></property> <property name="poolMinIdle" value="3"></property> </bean>
private static EmployeeDto getReceiverInfo(String receiver) { StoreKey key = new StoreKey(EMPLOYEE, receiver); ApplicationContext context = ContextLoader.getCurrentWebApplicationContext(); EmployeeDto dto = ((RedisStoreClient) context.getBean("redisClient")).get(key); if (dto != null) { return dto; } try { dto = ((EmployeeService) context.getBean("employeeService")).getByAd(receiver); } catch (Exception e) { LOGGER.error("employeeService.getByAd fail ", e); } return dto; }