配置文件:
<?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>
测试代码:
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();
}
}
静态工厂类
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>
实例工厂类
package com.shi.bean;
/*
* 使用实例工厂类创建bean3对象
*/
public class Bean3Factory {
public Bean3 getBean3(){
return new Bean3();
}
}
applicationContext.xml文件中的配置:
<!-- 使用实例工厂创建对象 -->
<!-- 先创建工厂对象 -->
<bean id="bean3Factory" class="com.shi.bean.Bean3Factory"></bean>
<bean id="bean3" factory-bean="bean3Factory" factory-method="getBean3"></bean>