首页 > 代码库 > spring注入bean的五种方式

spring注入bean的五种方式

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的五种方式