码迷,mamicode.com
首页 > 编程语言 > 详细

spring注入bean的五种方式

时间:2017-02-08 11:57:01      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:构造方法   creat   frame   throws   actor   scope   factor   blog   framework   

1.属性注入

2.构造方法注入

3.静态工厂注入

package com.voole.factorybeans;

import com.voole.beans.TestBean;

public class StaticFactoryBean {
    
    public static TestBean createInstance(){
        return new TestBean();
    }
    
}

<bean id="staticFactoryTestBean" class="com.voole.factorybeans.StaticFactoryBean" factory-method="createInstance" scope="prototype"></bean>


4.实例工厂注入

package com.voole.factorybeans;

import com.voole.beans.TestBean;

public class InstanceFactoryBean {
    
    public TestBean createTestBean(){
        return new TestBean();
    }
    
}


<bean id="instanceFactoryBean" class="com.voole.factorybeans.InstanceFactoryBean"></bean>
    
<bean id="instanceFactoryTestBean" factory-bean="instanceFactoryBean" factory-method="createTestBean" scope="prototype"></bean>

5.FactoryBean注入(这种方式最为简单)

package com.voole.factorybeans;

import org.springframework.beans.factory.FactoryBean;

import com.voole.beans.TestBean;

public class TestFactoryBean implements FactoryBean<TestBean>{

    @Override
    public TestBean getObject() throws Exception {
        return new TestBean();
    }

    @Override
    public Class<?> getObjectType() {
        return TestBean.class;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }

}

<bean id="testBean" class="com.voole.factorybeans.TestFactoryBean"></bean>

 

spring注入bean的五种方式

标签:构造方法   creat   frame   throws   actor   scope   factor   blog   framework   

原文地址:http://www.cnblogs.com/yzjT-mac/p/6377351.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!