1)作用:将自己的类交给IOC容器来负责,当需要每个类的对象时,不需要再通过
new 的关键字来造对象,直接从IOC容器中获取即可。
2)用法:
1》:通过bean标签来进行类的管理
bean标签的常用属性:
id:唯一标识
class:用于指明要管理的类(全类名)
scope:表示是单例模式(共用一个对象) 还是 多例模式(多个对象)
<bean id="helloworld" class="cn.wkl.spring.pojo.HelloWorld"></bean>
2》:bean 标签中可以嵌套 property 标签,用来表示对象的属性(有set方法)
name:就是属性名
value:就是属性值
<bean id="studentTwo" class="cn.wkl.spring.pojo.Student">
<!--依赖注入:为类型的属性赋值-->
<property name="age" value="18"></property>
<property name="gender" value="男"></property>
<property name="sid">
<null/> <!--将sid的值赋值为空指针-->
</property>
<property name="sname" value="独酌"></property>
</bean>
3》:bean对象的类类型的赋值
<bean id="studentThree" class="cn.wkl.spring.pojo.Student">
<property name="sname" value="张三"></property>
<property name="sid" value="01"></property>
<property name="gender" value="男"></property>
<property name="age" value="18"></property>
<!--为属性的实体类赋值 ref:引用某个bean的id-->
<property name="clazz" ref="clazzOne"></property>
</bean>
<bean id="clazzOne" class="cn.wkl.spring.pojo.Clazz">
<property name="cId" value="8"></property>
<property name="cName" value="战鼓擂"></property>
</bean>
4》:获取bean对象,并调用对象的方法
/*方法一:id + 类*/
//获取IOC容器
ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取bean
Student studentTwo = ioc.getBean("studentTwo", Student.class);
System.out.println(studentTwo);
/*方法二:id*/
//获取IOC容器
ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取bean
Student studentTwo = ioc.getBean("studentTwo");
System.out.println(studentTwo);
/*方法三:类*/
//获取IOC容器
ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取bean
Student studentTwo = ioc.getBean(Student.class);
System.out.println(studentTwo);
/*方法四:类所实现的接口*/
//获取IOC容器
ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取bean
Student studentTwo = ioc.getBean(StudentInterface.class);
System.out.println(studentTwo);

本文详细介绍了如何在Spring框架中使用IoC容器进行类的管理,包括bean标签的配置、不同方式获取bean对象以及依赖注入的使用。通过实例展示了如何通过id、类名、接口等方式获取对象并调用方法。
948

被折叠的 条评论
为什么被折叠?



