Spring 构造方法注入

在Spring中,一个bean只能为一个构造方法注入!

1、当只有个一个构造方法,且构造方式只有一个参数:

<bean id="user" class="com.clover.bean.User">
<constructor-arg value="boy" />
<property name="name" value="clover" />
<property name="age" value="26"></property>
</bean>


public User(String sex) {
this.sex = sex;
}
这个时候直接注入值即可,不用指定构造方法中参数的类型。

2、当构造方法有两个参数,Constructor-based DI会根据配置文件中代码顺序,为构造方法注入值。

<bean id="user" class="com.clover.bean.User">
<constructor-arg value="boy" />
<constructor-arg value="郑州" />
<property name="name" value="clover" />
<property name="age" value="26"></property>
</bean>


public User(String sex, String addr) {
this.sex = sex;
this.addr = addr;
}
所以,如果把参数的顺序搞错的话,会得到错误的值。如果构造方法的参数类型不一样就会报错。

在<constructor-arg />中指定type(参数类型)、index(文职)以及name(参数属性名)可以解决问题。

<bean id="user" class="com.clover.bean.User">
<constructor-arg name="age" index="1" type="int" value="26" />
<constructor-arg name="sex" index="0" type="java.lang.String" value="boy" />
</bean>


type、index和name在优先级上应该是平行的。不过,name用的时候有需要注意的地方。
Spring官方文档:[quote]Keep in mind that to make this work out of the box your code must be compiled with the debug flag enabled so that Spring can look up the parameter name from the constructor. If you can’t compile your code with debug flag (or don’t want to) you can use @ConstructorProperties JDK annotation to explicitly name your constructor arguments. [/quote]
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring 中,构造方法注入是一种依赖注入的方式,它通过构造方法来实现对依赖对象的注入。以下是如何在 Spring 中进行构造方法注入的步骤: 1. 创建需要被注入的依赖对象的类,并在该类的构造方法上添加 `@Autowired` 注解。 ```java public class Dependency { // 使用@Autowired 注解进行构造方法注入 @Autowired public Dependency() { // 构造方法逻辑 } } ``` 2. 在需要使用该依赖对象的类中,声明该依赖对象的成员变量,并在该成员变量上添加 `@Autowired` 注解。 ```java public class MyClass { // 使用@Autowired 注解进行构造方法注入 @Autowired private Dependency dependency; } ``` 3. 在 Spring 的配置文件(例如 applicationContext.xml)中,配置依赖对象和需要使用该对象的类。 ```xml <!-- 配置依赖对象 --> <bean id="dependency" class="com.example.Dependency" /> <!-- 配置需要使用该对象的类 --> <bean id="myClass" class="com.example.MyClass" /> ``` 这样,当 Spring 容器启动时,会自动识别 `@Autowired` 注解,并在初始化对象时自动将依赖对象注入到需要使用它的地方。注意,需要保证配置文件中已经正确引入了 Spring 的命名空间和依赖注入的约束。 除了使用 `@Autowired` 注解进行构造方法注入,还可以使用 `@Inject` 注解或者通过 XML 配置文件的方式实现构造方法注入。具体选择哪种方式取决于个人偏好和项目需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值