bean元素的属性及其子元素
属性或子元素名称 | 描述 |
---|---|
id | bean的唯一标识,代码中通过以此为索引创建实例 |
class | bean的实现类,使用类的完全限定名 |
scope | bean的作用域,默认为singleton |
<constructor-arg> | bean的构造函数参数 |
<property> | bean的setter属性 |
<list> | constructor-arg或property的子元素,用于向方法参数注入list或数组类型的参数值 |
<map> | constructor-arg或property的子元素,用于向方法参数注入map类型的参数值 |
<set> | constructor-arg或property的子元素,用于向方法参数注入set类型的参数值 |
<entry> | <map>的子元素,用于设置一个键值对 |
.
ddd
public interface TestDao {
public void sayHello();
}
public class Starter {
public static void main(String[] args) {
ApplicationContext context= new ClassPathXmlApplicationContext("classpath:application.xml");
TestDao dao= (TestDao)context.getBean("test");
dao.sayHello();
}
}
构造方法实例化
<bean id="test" class="demo1.dao.TestDaoImpl"></bean>
public class TestDaoImpl implements TestDao{
public void sayHello() {
System.out.println("hello kevin");
}
}
运行效果:hello kevin
静态工厂实例化
<bean id="test" class="demo1.dao.BeanFactory" factory-method="createInstance"></bean>
public class BeanFactory {
public static TestDao createInstance() {
TestDaoImpl dao= new TestDaoImpl();
dao.setName("kevin N");
return dao;
}
}
运行效果:hello kevin N
实例工厂实例化
<bean id="factory" class="demo1.dao.BeanFactory"></bean>
<bean id="test" factory-bean="factory" factory-method="createInstance"></bean>
public class BeanFactory {
public TestDao createInstance() {
TestDaoImpl dao= new TestDaoImpl();
dao.setName("kevin N");
return dao;
}
}