Spring IOC创建对象的两种方式

2025-05-29 0 73

ioc创建对象的方式

一、 使用无参构造创建对象(默认方式)

创建实体类

注意:属性必须要有set方法,来完成注入

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24
public class user {

private string name;

public user() {

system.out.println("执行了user类的无参构造方法~");

}

public user(string name){

this.name = name;

system.out.println("执行了user类的有参构造方法");

}

//使用无参构造方法时,必须要设置set方法,因为注入时 需要通过set方法注入

public void setname(string name) {

this.name = name;

}

@override

public string tostring() {

return "user{" +

"name='" + name + '\\'' +

'}';

}

}

配置bean

?

1

2

3

4

5

6

7

8

9

10

11
<?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

https://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="user" class="com.test.pojo.user">

<property name="name" value="gyp"/>

</bean>

</beans>

测试类

?

1

2

3

4

5

6

7
public class mytest {

public static void main(string[] args) {

applicationcontext context = new classpathxmlapplicationcontext("applicationcontext.xml");

user user = context.getbean("user", user.class);

system.out.println(user);

}

}

​ 结果:

Spring IOC创建对象的两种方式

二、使用有参构造创建对象

  • 通过下标注入
  • 通过名字注入 【推荐】
  • 通过类型注入

有参构造,不需要set方法注入

通过下标方式注入(通过index来选择,给有参构造的第几个参数注入

(1)配置bean

?

1

2

3
<bean id="user" class="com.test.pojo.user">

<constructor-arg index="0" value="gyp"/>

</bean>

(2)测试结果

Spring IOC创建对象的两种方式

通过名字注入

(1)配置bean

?

1

2

3
<bean id="user" class="com.test.pojo.user">

<constructor-arg name="name" value="gyp"/>

</bean>

(2)测试结果

Spring IOC创建对象的两种方式

通过类型注入(不建议使用!因为当类里面有两个相同类型的属性时,无法给属性注入

(1)配置bean

?

1

2

3
<bean id="user" class="com.test.pojo.user">

<constructor-arg type="java.lang.string" value="gyp"/>

</bean>

(2)测试结果

Spring IOC创建对象的两种方式

总结:在加载配置文件的时候,ioc就已经创建好了对象!

到此这篇关于spring ioc创建对象的两种方式的文章就介绍到这了,更多相关spring ioc创建对象内容请搜索快网idc以前的文章或继续浏览下面的相关文章希望大家以后多多支持快网idc!

原文链接:https://blog.csdn.net/XIaoyummm/article/details/114744961

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Spring IOC创建对象的两种方式 https://www.kuaiidc.com/108697.html

相关文章

发表评论
暂无评论