这篇文章主要介绍了spring基于xml文件配置bean过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
通过全类名来配置:
class:bean的全类名,通过反射的方式在ioc容器中创建bean,所以要求bean中必须有一个无参的构造器。
<bean id="helloworld" class="com.gong.spring.beans.helloworld"> <property name="name" value="jack"></property> </bean>
在springioc容器读取bean配置创建bean的实例之前,需要对容器进行实例化。spring提供了两种类型的ioc容器实现:
beanfactory:ioc容器的基本实现。
applicationcontext:提供了更多高级特性,是beanfactory的子接口。
applicationcontext主要实现类:
applicaiotncontex在初始化时就上下文时就实例化所有单例的bean。
webapplicationcontext是专门用于web应用的,它允许从相对于web根目录的路径中完成初始化工作。
依赖注入的三种方式
(1)属性注入:通过setter方法:<property name="name" value="jack"></property>,即在bean中存在setter方法。
(2)构造器注入:<constructor-arg value="" index="0" type=""></constructor-arg>,根据构造方法中初始化的参数进行一一设置,同时,可以根据参数的顺序index,参数的类型type来区分重载的构造器。
(3)工厂方法注入(很少使用,不推荐)
<bean id="student" class="com.gong.spring.beans.student"> //第一种方式注入属性值 <constructor-arg value="tom" index="0" type="java.lang.string"></constructor-arg> <constructor-arg value="12" index="1" type="int"></constructor-arg> //第二种方式注入属性值 <constructor-arg index="2" type="double"> <value>99.00</value> </constructor-arg> </bean>
package com.gong.spring.beans; public class student { private string name; private int age; private double score; public student(string name,int age,double score) { this.name = name; this.age = age; this.score = score; } @override public string tostring() { return "student [name=" + name + ", age=" + age + ", score=" + score + "]"; } }
public static void main(string[] args) { //1.创建spring的ioc容器对象 applicationcontext ctx = new classpathxmlapplicationcontext("applicationcontext.xml"); //2.从容器中获取bean实例 student student = (student) ctx.getbean("student"); system.out.println(student.tostring()); }
输出:
当属性值有特殊符号时,要用以下方式:
<constructor-arg index="0" type="java.lang.string"> <value><![cdata[<tom>]]></value> </constructor-arg>
用<![cdata[属性值]]>。
如对本文有疑问, 点击进行留言回复!!
【Nginx异常】[error] 4236#29900: OpenEvent(“Global\ngx_reload_27128“) failed (5: Access is denied)
解决jquery ajax中文传递到后端出现乱码问题 java
java8中使用java.util.Base64报“java.lang.IllegalArgumentException: Illegal base64 character d”
网友评论