配置文件: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>