spring 基于构造函数的依赖注入

    科技2026-02-20  8

    第一种情况:注入的是引用类型 不显式的指定构造函数参数索引或类型,此时构造函数注入的顺序必须可以任意,但是ThingTwo和ThingThree不应该存在继承关系 public class ThingOne { public ThingOne(ThingTwo thingTwo, ThingThree thingThree) { // ... } } <beans> <bean id="beanOne" class="x.y.ThingOne"> <constructor-arg ref="beanTwo"/> <constructor-arg ref="beanThree"/> </bean> <bean id="beanTwo" class="x.y.ThingTwo"/> <bean id="beanThree" class="x.y.ThingThree"/> </beans>

    2.第二种情况:注入的是普通类型 如果构造函数注入的顺序与参数顺序不一致,需要显式的指定构造函数参数索引或类型

    public class ExampleBean { // Number of years to calculate the Ultimate Answer private int years; // The Answer to Life, the Universe, and Everything private String ultimateAnswer; public ExampleBean(int years, String ultimateAnswer) { this.years = years; this.ultimateAnswer = ultimateAnswer; } } 使用type指定参数类型 <bean id="exampleBean" class="examples.ExampleBean"> <constructor-arg type="int" value="7500000"/> <constructor-arg type="java.lang.String" value="42"/> </bean> 使用index指定顺序 <bean id="exampleBean" class="examples.ExampleBean"> <constructor-arg index="0" value="7500000"/> <constructor-arg index="1" value="42"/> </bean> 使用name指定参数名称 <bean id="exampleBean" class="examples.ExampleBean"> <constructor-arg name="years" value="7500000"/> <constructor-arg name="ultimateAnswer" value="42"/> </bean> 引用类型与基本类型混合使用 只需要显式指定基本类型的参数索引或类型即可
    Processed: 0.029, SQL: 12