Spring Bean的配置和实例化

bean元素的属性及其子元素

属性或子元素名称描述
idbean的唯一标识,代码中通过以此为索引创建实例
classbean的实现类,使用类的完全限定名
scopebean的作用域,默认为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;
    }
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值