spring简单的搭建

类中要调用beanID的方式:
package com.itmg.factory;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import com.itmg.dao.CategoryDAO;

public class SpringBeanFactory {
	private static BeanFactory beanFactory;
	private static BeanFactory clientBeanFactory;
	static{
		try {
			Resource cresource = new ClassPathResource("applicationContext.xml");
			beanFactory = new XmlBeanFactory(cresource);
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			Resource clientCresource = new ClassPathResource("appClientContext.xml");
			clientBeanFactory = new XmlBeanFactory(clientCresource);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static Object getBeanByID(String beanID) {
		return beanFactory.getBean(beanID);
	}
	public static Object getRemoteBeanByID(String beanID) {
		return clientBeanFactory.getBean(beanID);
	}
	
	public static void main(String[] args) {
		CategoryDAO dao = (CategoryDAO)SpringBeanFactory.getBeanByID("categoryDAO");
		System.out.println(dao);
	}
}

web.xml中要配置一下
<context-param>	
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>
 	<listener>
    	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  	</listener>

这样就ok了

你可能感兴趣的:(java,DAO,spring,xml,Web)