获取Spring中ApplicationContext.xml的Bean

package org.sunnysolong.web.mvc.test;

 

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import org.springframework.context.support.FileSystemXmlApplicationContext;

import org.springframework.core.io.ClassPathResource;

import org.springframework.core.io.FileSystemResource;

import org.springframework.core.io.Resource;

import org.sunnysolong.web.mvc.service.UserService;

 

 

/**

* Title: mvcs<br>

* Description: Get Spring Application Context<br>

* Copyright: Copyright (c) 2011 <br>

* Create DateTime: Jul 21, 2011 3:21:49 PM <br>

* @author wangmeng

*/

public class Commision {

 

@SuppressWarnings("deprecation")

public static void main(String[] args){

Resource resource = new FileSystemResource("WebRoot/WEB-INF/config/applicationContext.xml");

BeanFactory oneFac = new XmlBeanFactory(resource);

UserService oneUs = (UserService) oneFac.getBean("userService");

System.out.println(oneUs.notice());

 

//the classpathContext.xml is in the classpath directory.

ClassPathResource cpResource = new ClassPathResource("classpathContext.xml");

BeanFactory twoFac = new XmlBeanFactory(cpResource);

UserService twoUs = (UserService) twoFac.getBean("userService");

twoUs.say();

ApplicationContext ctxSt = new FileSystemXmlApplicationContext("/WebRoot/WEB-INF/config/applicationContext.xml");

UserService threeUs = (UserService) ctxSt.getBean("userService");

System.out.println(threeUs.notice());

ApplicationContext ctxNd = new ClassPathXmlApplicationContext("file:WebRoot/WEB-INF/config/applicationContext.xml");

UserService fourUs = (UserService) ctxNd.getBean("userService");

fourUs.say();

}

}


你可能感兴趣的:(spring,beanfactory)