spring注入bean的五种方式
Posted 麦子TMAC
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的五种方式的主要内容,如果未能解决你的问题,请参考以下文章