导入jar包 还有commons-logging-1.1.1.jar这个包 在src目录下创建bean.xml文件 导入约束
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- bean definitions here --> <!-- 配置资源:把对象创建交给spring管理 根据class的类名反射创建类 --> <bean id="customerService" class="service.impl.CustomerServiceImpl"></bean> <bean id="customerDao" class="dao.impl.CustomerDaoImpl"></bean> <!-- 配置使用静态工厂来创建bean对象 --> <bean id="StaticCustomerService" class="factory.StaticCustomerFactory" factory-method="getCustomerService"></bean> <!-- 配置使用实例工厂来创建bean对象 --> <bean id="instanceFactory" class="factory.InstanceFactory"></bean> <bean id="instanceCustomerService" factory-bean="instanceFactory" factory-method="getCustomerService"></bean> </beans>创建bean对象
public static void main(String[] args) { //获取容器 ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); System.out.println("---------------------"); //根据bean的id获取对象 //CustomerService customerService = (CustomerService) ac.getBean("customerService"); //使用静态工厂创建对象 //CustomerService customerService = (CustomerService) ac.getBean("StaticCustomerService"); //使用实例工厂创建对象 //CustomerService customerService = (CustomerService) ac.getBean("instanceCustomerService"); //CustomerDao customerDao = (CustomerDao) ac.getBean("customerDao");; //System.out.println(customerService); }