Spring的两种依赖注入方式-setter方法注入与构造方法注入

Spring的两种依赖注入方式-setter方法注入与构造方法注入Spring 的两种依赖注入方式 setter 注入与构造方法注入 这两种方法的不同主要就是在 xml 文件下对应使用 property 和 constructor arg 属性 例如 property 属性

大家好,我是讯享网,很高兴认识大家。

   Spring的两种依赖注入方式:setter注入与构造方法注入,这两种方法的不同主要就是在xml文件下对应使用property和constructor-arg属性, 例如:

property属性:<property name="id" value="123"></property>(其中name的值为原类中的属性名)

constructor-arg属性:<constructor-arg index="0" value="456"></constructor-arg>(其中index的值为0~n-1,n代表构造函数中的输入参数的数量)


1.setter方法注入


讯享网

   setter方法注入即是创建一个普通的JavaBean类,为需要注入的属性通过对应的setter方法即可,如:

(1)创建一个Id类:

package com.loster.li; public class Id { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }

讯享网 (2)创建配置文件Id_Bean.xml
讯享网<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="id" class="com.loster.li.Id"> <property name="id" value="123"></property> <property name="name" value="xiaoli"></property> </bean> </beans>
(3)编写测试类IdTest.java,并运行:
package com.loster.li; import org.springframework.context.support.ClassPathXmlApplicationContext; public class IdTest { public static void main(String[] args){ ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("com/loster/li/Id_Bean.xml"); Id id = (Id)context.getBean("id"); System.out.println(id.getId()); System.out.println(id.getName()); } }
    运行结果如下:

小讯
上一篇 2025-02-06 10:07
下一篇 2025-04-10 15:28

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/82108.html