0
点赞
收藏
分享

微信扫一扫

spring application.xml在项目中的几种解析方式


解析 在java项目中的spring applicationContext.xml文件的几种解析方式:

一种:

ApplicationContext cxt = new ClassPathXmlApplicationContext(“applicationContext.xml”);

cxt.getBean(“在applicationContext.xml中bean的id”);


二种:

ApplicationContext cxt =

new FileSystemXmlApplicationContext(“applicationContext.xml的绝对路径”);

cxt.getBean(“在applicationContext.xml中bean的id”);


三种:

Resource res= new ClasspathResource(“applicationContext.xml”);

XmlBeanFactory factory = new XmlBeanFactory(res);

factory.getBean(“applicationContext.xml中的bean的id”);



第四种:在web项目中解析applicationContext.xml,此方法本人感觉很好用,如在struts2.0+hibernate3.0+sprnig2.0中,某jsp页面须用daoImpl(业务实现类的一个方法),一般写法是在action中调用该方法,写不可以直接使用,因为所有东东都交给spring管理了,但是在原来的基础上加上以下这个类,做法就多了,我们可以在该jsp页面用<s:bean id="aa" name="org.xxxx.Gean"> <s:set name="bb" value="%{#aa.getBean('此处为applicationContext.xml中所写的daoImpl的bean的id')}"> bb就是我们所要的方法的返回值.

public class GetBean {

private XmlBeanFactory factory;

public GetBean()

{

Resource res=new ServletContextResource(ServletActionContext.getServletContext(),"/WEB-INF/transaction.xml");

factory=new XmlBeanFactory(res);

}

public Object getBean(String beanname)

{

XmlWebApplicationContext ctx=new XmlWebApplicationContext();

ServletContext servletcontext=ServletActionContext.getServletContext();

ctx.setServletContext(servletcontext);

ctx.setConfigLocations(new String[]{"/WEB-INF/transaction.xml"});

ctx.refresh();//由servletContext初始化beanfactory需要的配置文件,进而加载该配置文件

Object obj=ctx.getBean(beanname);

return obj;

}

}


举报

相关推荐

0 条评论