这篇文章将为大家详细讲解有关怎么在春天中利用xml文件配置Bean,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
通过全类名来配置:
类:Bean的全类名,通过反射的方式在国际奥委会容器中创建Bean,所以要求Bean中必须有一个无参的构造器。
,, & lt; bean id=癶elloWorld",类=癱om.gong.spring.beans.HelloWorld"比; ,,,& lt; property name=皀ame",价值=https://www.yisu.com/zixun/"杰克"> 属性> 豆>
在springIOC容器读取豆配置创建bean的实例之前,需要对容器进行实例化.spring提供了两种类型的国际奥委会容器实现:
Beanfactory:国际奥委会容器的基本实现。
ApplicationContext:提供了更多高级特性,是Beanfactory的子接口。
ApplicationContext主要实现类:
- <李>
ClassPathXmlApplicationContext:从类路径加载配置文件。
李> <李>FileSystemXmlApplicationContext:从文件系统中加载配置文件。
李> <李>ConfigureableApplicationContext扩展于ApplicationContext,新增两个方法refresh()和()关闭,让ApplicationContext具有启动,刷新和关闭上下文的能力。
李>ApplicaiotnContex在初始化时就上下文时就实例化所有单例的bean。
WebApplicationContext是专门用于网络应用的,它允许从相对于WEB根目录的路径中完成初始化工作。
<强>依赖注入的三种方式强>
(1)属性注入:通过setter方法:& lt;属性名=皀ame"值=https://www.yisu.com/zixun/"杰克"> 属性>,即在bean中存在setter方法。
(2)构造器注入:& lt; constructor-arg价值=https://www.yisu.com/zixun/薄爸甘? " 0 " type=" "> ,根据构造方法中初始化的参数进行一一设置,同时,可以根据参数的顺序指数,参数的类型类型来区分重载的构造器。
(3)工厂方法注入(很少使用,不推荐)
& lt; bean id=皊tudent",类=癱om.gong.spring.beans.Student"在,,,,//第一种方式注入属性值 ,,,& lt; constructor-arg 价值=https://www.yisu.com/zixun/疤滥贰敝甘? " 0 " type="以">//第二种方式注入属性值 <价值> 值> 99.00 豆>
package com.gong.spring.beans; public class  Student { private 才能;String 名称; private 才能;int 年龄; private 才能;double 分数; public 才能;学生(double  String 姓名、int 年龄;分数),{ ,,,this.name =,名称; ,,,this.age =,年龄; ,,,this.score =,分数; ,,} @Override才能 public 才能;String  toString (), { ,,,return “Student [name=? +, name +,,,,岁=?+,age +,,,,分数=?+,score +,“]”; ,,} ,, }
public static void main (String [], args), { ,,,//1。创建spring的IOC容器对象 ,,,ApplicationContext ctx =, new ClassPathXmlApplicationContext (“applicationContext.xml"); ,,,//2。从容器中获取豆实例 ,,,Student Student =,(学生),ctx.getBean (“student");, ,,,System.out.println (student.toString ()); 以前,,}>输出:
& lt; constructor-arg 指数=?“,类型=癹ava.lang.String"比; ,,,,,& lt; value> & lt; ! [CDATA [& lt; tom>]]祝辞& lt;/value> ,,,& lt;/constructor-arg>
关于怎么在春天中利用xml文件配置Bean就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看的到。