Bean实例化的三种方式
无参构造方法实例化
userimpl 为接口实现类
demo 为测试类
UserDao 为接口
package cn.impl;
import cn.user.UserDao;
public class userimpl implements UserDao {
@Override
public void say() {
System.out.println("hello!");
}
}
package cn.user;
public interface UserDao {
public abstract void say();
}
package cn.text;
import cn.user.UserDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class demo1 {
public static void main(String[] args) {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao = (UserDao) app.getBean("userDao");
userDao.say();
}
}
在 Spring配置文件中配置 bean
<bean id ="UserDao" class = "cn.impl.userimpl"> <bean>
输出结果 :
工厂静态方法实例化
创建工厂静态方法
package cn.factory;
import cn.impl.userimpl;
import cn.user.UserDao;
public class userFactory {
static UserDao getUserDao(){
return new userimpl();
}
}
bean配置
<bean id ="UserDao" class="cn.factory.userFactory" factory-method="getUserDao"></bean>
工厂实例方法
import cn.impl.userimpl;
import cn.user.UserDao;
public class eampleFactory {
public UserDao getUserDao(){
return new userimpl();
}
}
bean 配置
<bean id="example" class="cn.factory.eampleFactory"></bean>
<bean id="UserDao" factory-bean="example" factory-method="getUserDao"></bean>
本文来自博客园,作者:冰莫莫,转载请注明原文链接:https://www.cnblogs.com/icemomo/p/16000800.html