spring bean配置记录
scope: singleton, prototype, request, session, globle sesssion
默认为singleton
id和name的区别:
id是唯一标识bean.不能用特殊字符:×#@ ,不能用数字开头。在bean引用的时候只能有id指向你需要的bean
name 可以用特殊字符,并且一个bean可以用多个名称:name=“bean1,bean2,bean3” ,用逗号隔开。如果没有id,则name的第一个名称默认是id
通过id和name都可以取出该Bean.
<bean id=“thisbean” name=“bean1,bean2,bean3” class=“org.example.Dao" />
BeanFactory factory=new XmlBeanFactory(new ClassPathResource("config.xml"));
bean definition inheritance(bean 定义继承)
1 配置文件继承
<bean id="baseDaoImpl" abstract="true">
<property name="name" value="baseName"></property>
<property name="age" value="11"></property>
</bean>
<bean id="testDaoImpl" class="main.daoImpl.TestDaoImpl" parent="baseDaoImpl">
<property name="age" value="1"></property>
</bean>
如上所示:testDaoImpl的bean配置了baseDaoImpl的配置,bean没有指定具体class,如果子配置没有配置具体的属性,则从父配置中继承;如果配置了则覆盖父配置中的值
2 类继承配置
java类:
public class BaseDaoImpl extends HibernateDaoSupport {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class TestDaoImpl extends BaseDaoImpl {
}
对应spring配置:
<bean id="baseDaoImpl" class="main.daoImpl.BaseDaoImpl" abstract="true">
<property name="name" value="baseName"></property>
<property name="age" value="11"></property>
<property name="sessionFactory" ref="mySessionFactory"></property>
</bean>
<bean id="testDaoImpl" class="main.daoImpl.TestDaoImpl" parent="baseDaoImpl">
<property name="age" value="1"></property>
</bean>
<bean id="testService" class="main.service.TestService">
<constructor-arg index="0" ref="testDaoImpl"></constructor-arg>
</bean>
测试代码:
@Test
public void testA() throws IOException {
try {
TestService testService = (TestService)context.getBean("testService");
TestDaoImpl testDaoImpl = testService.getTestDaoImpl();
System.out.println("name: " + testDaoImpl.getName() + " age:" + testDaoImpl.getAge() + " sessionFactory:" + testDaoImpl.getSessionFactory());
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
测试结果:name: baseName age:1 sessionFactory:org.hibernate.impl.SessionFactoryImpl@b02928
baeDaoImpl类在配置文件中配置成了abstract,不能再进行实例化,如果尝试去实例化会报错!