博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java_web开发_SSH spring中取得Bean实例的方法
阅读量:4125 次
发布时间:2019-05-25

本文共 8307 字,大约阅读时间需要 27 分钟。

获得spring里注册Bean的四种方法,特别是第三种方法,简单:

一:方法一(多在struts框架中)继承BaseDispatchAction

 

  

二:方法二实现BeanFactoryAware
一定要在spring.xml中加上:
<bean id="serviceLocator" class="项目中ServiceLocator的类路径比如:com.am.oa.commons.service.SpringContextUtil " singleton="true" />
当对serviceLocator实例时就自动设置BeanFactory,以便后来可直接用beanFactory

  

action调用:

 

  

三:方法三实现ApplicationContextAware
一定要在spring.xml中加上:
<bean id="SpringContextUtil " class="项目中applicationContext的类路径比如:com.am.oa.commons.service.SpringContextUtil " singleton="true" />
当对SpringContextUtil 实例时就自动设置applicationContext,以便后来可直接用applicationContext
 
  

 

action调用: 

  

 

四.通过servlet 或listener设置spring的ApplicationContext,以便后来引用.

注意分别extends  ContextLoaderListener和ContextLoaderServlet .然后就可用SpringContext来getBean.
覆盖原来在web.xml中配置的listener或servlet.

  

 

自己使用:

 

1.如果applicationContext文件是在src的根目录下:

  ApplicationContext apt= new FileSystemXmlApplicationContext("src/applicationContext.xml");

apt.getBean("ID");

可以取得

 

2.如果文件是在WebRoot/WEB-INF下可以用

ApplicationContext applicationContext= new FileSystemXmlApplicationContext("../applicationContext.xml");

取得

 

3.如果是在servlet中取可用

  ServletContext application = this.getServletContext();

  
  //获取spring上下文信息 为servlet使用
  WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(application);
  IDicService dicService = (IDicService)wac.getBean("dicService");

 

转载地址:http://tclpi.baihongyu.com/

你可能感兴趣的文章
WebRequest post读取源码
查看>>
使用TcpClient可避免HttpWebRequest的常见错误
查看>>
EntityFramework 学习之一 —— 模型概述与环境搭建 .
查看>>
C# 发HTTP请求
查看>>
启动 LocalDB 和连接到 LocalDB
查看>>
Palindrome Number --回文整数
查看>>
Reverse Integer--反转整数
查看>>
Container With Most Water --装最多水的容器(重)
查看>>
Longest Common Prefix -最长公共前缀
查看>>
Letter Combinations of a Phone Number
查看>>
Single Number II --出现一次的数(重)
查看>>
Valid Parentheses --括号匹配
查看>>
Remove Element--原地移除重复元素
查看>>
Remove Duplicates from Sorted Array--从有序数组中移除重复元素
查看>>
Count and Say
查看>>
Gas Station
查看>>
Palindrome Partitioning --回文切割 深搜(重重)
查看>>
Valid Palindrome 简单的回文判断
查看>>
Pascal's Triangle -- 生成杨辉三角
查看>>
Pascal's Triangle II 生成杨辉三角中的某行
查看>>