欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

获取Spring中ApplicationContext.xml的Bean 博客分类: Spring SpringBeanFactoryApplicationContext 

程序员文章站 2024-02-06 11:52:40
...

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();

}

}