好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Spring IOC创建对象的两种方式

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://HdhCmsTestspringframework.org/schema/beans"

     xmlns:xsi= "http://HdhCmsTestw3.org/2001/xmlschema-instance"

     xsi:schemalocation="http: //HdhCmsTestspringframework.org/schema/beans

     https: //HdhCmsTestspringframework.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);

   }

}

? 结果:

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

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

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

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

(1)配置bean

?

1

2

3

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

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

</bean>

(2)测试结果

通过名字注入

(1)配置bean

?

1

2

3

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

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

</bean>

(2)测试结果

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

(1)配置bean

?

1

2

3

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

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

</bean>

(2)测试结果

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

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

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

查看更多关于Spring IOC创建对象的两种方式的详细内容...

  阅读:11次