天天看点

java spring bean配置文件_Spring基于xml文件配置Bean过程详解

这篇文章主要介绍了spring基于xml文件配置Bean过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

通过全类名来配置:

class:bean的全类名,通过反射的方式在IOC容器中创建Bean,所以要求bean中必须有一个无参的构造器。

在springIOC容器读取Bean配置创建Bean的实例之前,需要对容器进行实例化。spring提供了两种类型的IOC容器实现:

beanfactory:IOC容器的基本实现。

ApplicationContext:提供了更多高级特性,是beanfactory的子接口。

ApplicationContext主要实现类:

ClassPathXmlApplicationContext:从类路径加载配置文件。

FileSystemXmlApplicationContext:从文件系统中加载配置文件。

ConfigureableApplicationContext扩展于ApplicationContext,新增两个方法refresh()和close(),让ApplicationContext具有启动、刷新和关闭上下文的能力。

ApplicaiotnContex在初始化时就上下文时就实例化所有单例的Bean。

WebApplicationContext是专门用于WEB应用的,它允许从相对于WEB根目录的路径中完成初始化工作。

依赖注入的三种方式

(1)属性注入:通过setter方法:,即在bean中存在setter方法。

(2)构造器注入:,根据构造方法中初始化的参数进行一一设置,同时,可以根据参数的顺序index,参数的类型type来区分重载的构造器。

(3)工厂方法注入(很少使用,不推荐)

//第一种方式注入属性值

//第二种方式注入属性值

99.00

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());

}

java spring bean配置文件_Spring基于xml文件配置Bean过程详解

当属性值有特殊符号时,要用以下方式:

]]>

用。

相关文章

总结

如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。

如您喜欢交流学习经验,点击链接加入交流1群:1065694478(已满)交流2群:163560250