需要用到的几个类:
-
IUserService :
public interface IUserService {
public void add();
}
-
UserServiceImpl:
public class UserServiceImpl implements IUserService{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public void add() {
System.out.println("创建用户...." + name);
}
}
1. 使用构造方法实例化
- beans.xml:
<!-- 第一种方式: new 实现类-->
<bean id="userService" class="com.lkp.service.UserServiceImpl">
<property name="name" value="summer"></property>
</bean>
- test方法:
public void test1() {
//new 对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
IUserService user = (IUserService) context.getBean("userService");
user.add();
}
2 使用静态工厂方法实例化
- UserServiceFactory1:
public class UserServiceFactory1 { public static IUserService createUserService(){ return new UserServiceImpl() ; } }
- beans.xml:
<!-- 第二种: 通过静态工厂方法--> <bean id="userService2" class="com.lkp.service.UserServiceFactory1" factory-method="createUserService"> <property name="name" value="summer"></property> </bean>
- test方法:
public void test1() { //静态工厂 ApplicationContext context = new ClassPathXmlApplicationContext("beans3.xml"); IUserService userService = (IUserService) context.getBean("userService2"); userService.add(); }
3 使用实例工厂方法实例化
- UserServiceFactory1:
public class UserServiceFactory2 {
public IUserService createUserService() {
return new UserServiceImpl();
}
}
- beans.xml:
<!--第三种 实例工厂方法--> <!-- 创建实例factory2 bean--> <bean id="factory2" class="com.lkp.service.UserServiceFactory2" /> <bean id="userService3" factory-bean="factory2" factory-method="createUserService"></bean>
- test方法:
public void test1() { //实例工厂 创建工厂 UserServiceFactory2 factory2 = new UserServiceFactory2(); IUserService userService3 = factory2.createUserService(); userService3.add(); }