1 Bean标签基本配置
用于配置对象交由Spring来创建。
默认情况下它调用的是类中的无参构造函数,如果没有无参构造函数则不能创建成功。
基本属性:
●id: Bean实例在Spring容器中的唯一标识
●class: Bean的全限定名称
2 Bean标签范围配置
scope:指对象的作用范围,取值如下:
//测试scope属性
public void test1(){
ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao1 = (UserDao)app.getBean("userDao");
UserDao userDao2 = (UserDao)app.getBean("userDao");
System.out.println(userDao1);
System.out.println(userDao2);
}
当scope=“prototype”
scope=“singleton”
3 Bean实例化三种方式
public class UserDaoImpl implements UserDao {
public UserDaoImpl() {
System.out.println("UserDaoImpl创建");
}
public void init(){
System.out.println("初始化方法");
}
public void destory()
{
System.out.println("销毁方法");
}
public void save() {
System.out.println("Spring");
}
}
无参构造方法实例化
<bean id="userDao" class="com.ruan.impl.UserDaoImpl" >
厂静态方法实例化
public class StaticFactory {
public static UserDao getUserDao(){
return new UserDaoImpl();
}
}
<bean id="userDao" class="com.ruan.factory.StaticFactory" factory-method="getUserDao" ></bean>
厂实例方法实例化
public class DynamicFactory {
public UserDao getUserDao(){
return new UserDaoImpl();
}
}
<bean id="factory" class="com.ruan.factory.DynamicFactory" ></bean>
<bean id="userDao" factory-bean="factory" factory-method="getUserDao"/></beans>
引用其它配置文件