Bean 的四种构造方式
程序员文章站
2022-03-06 13:35:03
...
1.通过构造函数创建
<bean id='injectBean' class="di.InjectBean"></bean> <bean id="diConstruct" class="di.DependencyInjectConstruct"> <constructor-arg type="java.lang.String" value="Inject construct test"/> <constructor-arg ref="injectBean"/> </bean>
package di; public class DependencyInjectConstruct { private final String value; private final InjectBean injectBean; public DependencyInjectConstruct(String value, InjectBean injectBean) { this.value = value; this.injectBean = injectBean; } public void print() { System.out.println(value); System.out.println(injectBean); } }
2.通过Setter注入
<bean id="diSetter" class="di.DependencyInjectSetter"> <property name="value" value="Inject setter test"/> <property name="injectBean" ref="injectBean"/> </bean>
package di; public class DependencyInjectSetter { private String value; private InjectBean injectBean; public void setValue(String value) { this.value = value; } public void setInjectBean(InjectBean injectBean) { this.injectBean = injectBean; } @Override public String toString() { return "DependencyInjectSetter [value=" + value + ", injectBean=" + injectBean + "]"; } }
3.通过工厂方法
<bean id="diStaticMethod" class="di.DependencyInjectStaticMethod" factory-method="create"></bean>
package di; public class DependencyInjectStaticMethod { private final String value; private final InjectBean injectBean; private DependencyInjectStaticMethod(String value, InjectBean injectBean) { this.value = value; this.injectBean = injectBean; } public static DependencyInjectStaticMethod create() { return new DependencyInjectStaticMethod("Dependency inject for status method", new InjectBean()); } @Override public String toString() { return "DependencyInjectStaticMethod [value=" + value + ", injectBean=" + injectBean + "]"; } }
4.如果需要的非static的工厂方法可以用factory-bean类引用一个对象来创建bean
<bean id="factoryBean" class="di.DependencyInjectMethod"></bean> <bean id="diMethod" class="di.DependencyInjectStaticMethod" factory-bean="factoryBean" factory-method="create"></bean>
package di; public class DependencyInjectMethod { private String value; private InjectBean injectBean; public DependencyInjectMethod() { } private DependencyInjectMethod(String value, InjectBean injectBean) { this.value = value; this.injectBean = injectBean; } public DependencyInjectMethod create() { return new DependencyInjectMethod("Dependency inject for method", new InjectBean()); } @Override public String toString() { return "DependencyInjectMethod [value=" + value + ", injectBean=" + injectBean + "]"; } }