1.无参构造方法实例化(详见我的博客)
2.工厂静态方法实例化
创建StaticFactory类

public class StaticFactory {
public static UserDao getUserDao(){
return new UserDaoImpl();
}
}

UserDaoImpl类

public class UserDaoImpl implements UserDao {

public UserDaoImpl(){
System.out.println("UserDaoImpl被创建了");
}

@Override
public void save() {
System.out.println("save running...");
}
}

配置applicationContext.xml文件
告诉spring使用什么实例化

<?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 id="userDao" class="com.hao.dao.impl.UserDaoImpl" ></bean>-->

<bean id="userDao" class="com.hao.factory.StaticFactory" factory-method="getUserDao"></bean>
</beans>

其中的class是静态类的全限定类名,factory-method是静态类中的方法名,因为该类是静态的,所以不需要创建该类对象,直接调用即可
然后测试

public class SpringTest {

@Test
//测试scope属性
public void test1(){
ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao1 = (UserDao) app.getBean("userDao");
System.out.println(userDao1);
}
}

Spring配置文件-Bean实例化的三种方式_spring


3.工厂实例方法实例化

创建工厂类DynamicFactory

public class DynamicFactory {
public UserDao getUserDao(){
return new UserDaoImpl();
}
}

application的配置

<?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">

<!-- 让spring先创建factory工厂对象-->
<bean id="factory" class="com.hao.factory.DynamicFactory"></bean>
<!-- 配置userDao的唯一标识id,factory-bean表示我要找这个factory工厂,然后找到找到getUserDao方法-->
<bean id="userDao" factory-bean="factory" factory-method="getUserDao"></bean>
</beans>