Java获取Spring中配置的Bean的三种方式

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;

public class Test {
    /**
     * 获取bean工厂(第一种方式)
     * 
     * @param filePath
     *            相对路径 注意:文件必须在类路径下
     *            比如:applicationContext.xml文件在包com.xieke.test下,
     *            路径就是/com/xieke/test/applicationContext.xml
     * @return
     */
    @SuppressWarnings("deprecation")
    public static BeanFactory getBeanFactory(String filePath)
    {
        return new XmlBeanFactory(new ClassPathResource(filePath));
    }

    /**
     * 获取bean工厂(第二种方式)
     * 
     * @param filePath
     *            相对路径 注意:文件必须在类路径下
     *            比如:applicationContext.xml文件在包com.xieke.test下,
     *            路径就是/com/xieke/test/applicationContext.xml
     * @return
     */
    public static ApplicationContext getApplicationContext(String filePath)
    {
        return new ClassPathXmlApplicationContext(filePath);
    }

    /**
     * 获取bean工厂(第三种方式)
     * 
     * @param filePath
     *            绝对路径或相对路径 如果是相对路径,则从当前项目下的目录开始计算, 
     *            如:当前项目/WebContent/WEB-INF/applicationContext.xml,
     *            相对路径就是/WebContent/WEB-INF/applicationContext.xml
     * @return
     */
    public static ApplicationContext getContext(String filePath)
    {
        return new FileSystemXmlApplicationContext(filePath);
    }

    public static <T> void printBean(BeanFactory beanFactory, String beanId, Class<T> className)
    {
        System.out.println(beanFactory.getBean(beanId, className));
    }

	public static void main(String[] args) {
		
        BeanFactory beanFactory = getBeanFactory("/com/xieke/test/applicationContext.xml");
        printBean(beanFactory, "userBean", User.class);
        printBean(beanFactory, "userBean2", User.class);

        ApplicationContext applicationContext = getApplicationContext("/com/xieke/test/applicationContext.xml");
        printBean(applicationContext, "userBean", User.class);
        printBean(applicationContext, "userBean2", User.class);
		
        ApplicationContext context = getContext("/WebContent/WEB-INF/applicationContext.xml");
        printBean(context, "userBean", User.class);
        printBean(context, "userBean2", User.class);
	}

}

 

   转载请注明出处: http://xieke90.iteye.com/blog/2234803

 

你可能感兴趣的:(spring ioc,spring bean,java bean)