配置文件:web
<?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"> <!-- ioc入门 --> <bean id="userService" class="com.shi.service.UserService"></bean> </beans>
测试代码:spring
package com.shi.service; import org.junit.Before; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class UserServiceTest { @Before public void setUp() throws Exception { } @Test public void test() { //1 加载spring配置文件,根据建立对象 ApplicationContext applicationContext= new ClassPathXmlApplicationContext("classpath:spring/applicationContext-service.xml"); //2 获取容器中建立的对象 UserService userService=(UserService) applicationContext.getBean("userService"); UserService userService2=(UserService) applicationContext.getBean("userService"); System.out.println(userService); System.out.println(userService2);//俩次获取的是同一个对象 userService.add(); } }
静态工厂类app
package com.shi.bean; /* * 使用静态类工厂建立bean2对象 */ public class Bean2Factory { public static Bean2 getBean2(){ return new Bean2(); } }
applicationContext.xml文件中的配置:测试
<!-- 使用静态工厂建立对象 --> <bean id="ben2Factory" class="com.shi.bean.Bean2Factory" factory-method="getBean2"></bean>
实例工厂类spa
package com.shi.bean; /* * 使用实例工厂类建立bean3对象 */ public class Bean3Factory { public Bean3 getBean3(){ return new Bean3(); } }
applicationContext.xml文件中的配置:code
<!-- 使用实例工厂建立对象 --> <!-- 先建立工厂对象 --> <bean id="bean3Factory" class="com.shi.bean.Bean3Factory"></bean> <bean id="bean3" factory-bean="bean3Factory" factory-method="getBean3"></bean>