4. Spring 如何通过 XML 文件配置Bean,以及如何获取Bean

在 Spring 容器内拼凑 bean 叫做装配。装配 bean 的时候,你是在告诉容器,需要哪些 bean ,以及容器如何使用依赖注入将它们配合在一起。

理论上,bean 装配的信息可以从任何资源获得,包括属性文件,关系数据库等,但 XML 文件是最常见的 Spring 应用系统配置源, Spring 中的几种容器都支持使用 XML 装配 bean,包括:

  --XMLBeanFactory

  --ClassPathXMLApplicationContext

  --FileSystemXMLApplicationContext

  --XMLWebApplicationContext

其中我们常用的有 ClassPathXMLApplicationContext,FileSystemXMLApplicationContext 两种。

 

在 XML 文件中配置 bean 包括以下几个方面:

  1. 添加 bean

  2. 配置 bean 属性

    2.1 手动配置

      2.1.1 通过 setter 方法

      2.1.2 通过 constructor

    2.2 自动配置

 

下面,我们来添加 bean,并通过 setter 方法来对 bean 的属性来进行配置:

  首先,先写两个 bean ,分别是 Person 和 Address , 其中 Person 是依赖于 Address 的。下面附上代码:

package com.spring.xmlBean;public class Person {private String name;private int age;private Address address;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public Address getAddress() {return address;}public void setAddress(Address address) {this.address = address;}public Person(String name, int age, Address address) {super();this.name = name;this.age = age;this.address = address;}public Person() {super();}@Overridepublic String toString() {return "Person [name=" + name + ", age=" + age + ", address=" + address + "]";}}
Person 类
package com.spring.xmlBean;public class Person {private String name;private int age;private Address address;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public Address getAddress() {return address;}public void setAddress(Address address) {this.address = address;}public Person(String name, int age, Address address) {super();this.name = name;this.age = age;this.address = address;}public Person() {super();}@Overridepublic String toString() {return "Person [name=" + name + ", age=" + age + ", address=" + address + "]";}}
Address 类

  类写完之后,我们在 classpath 下创建一个 Spring Bean Configuration File

创建完 XML 文件之后,我们开始在这个文件里配置 Bean。

首先,第一步:添加 bean

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!-- 添加 Address 和 Person --><bean id="address" class="com.spring.xmlBean.Address"></bean><bean id="person" class="com.spring.xmlBean.Person"></bean>
</beans>
Spring Bean Configuration File

在这里,我们通过 <bean></bean> 节点来添加 bean ,其中 class 属性代表 bean 的全类名, id 属性用来对 bean 进行标示,在调用 bean 的时候会使用这个 id 名,这个名字是唯一的,在配置文件中不能有重复,否则 Spring 会报错

添加完 bean 之后,我们先来测试一下,看能不能获取到这个 bean。我们先试着获取一下 Person

package com.spring.test;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;import com.spring.helloworld.HelloWorld;
import com.spring.xmlBean.Person;public class TestMain {public static void main(String[] args) {// 创建 Spring 的 IOC 容器ApplicationContext ctx = new ClassPathXmlApplicationContext("beanConfiguration-xml.xml");// 使用 getBean() 方法, 通过传入刚才的 id 名,来获取 bean, 但是这里返回的是一个 Object 对象, 所以要转型Person person = (Person) ctx.getBean("person");// 打印 person
        System.out.println(person);}
}
TestMain

运行 main 方法,控制台输出了以下信息

我们看到,我们成功的获取到了 person,但是,person 中的属性是空的,因为我们还没有配置他们,只是单纯的把它们添加到容器里面

那么现在,我们就来手动配置一下这两个 bean

前面讲过,手动配置 bean 有两种方式,一种是通过 setter 方法,一种是通过 构造器(constructor)来配置。下面,我们都试一下:

1. 通过 setter 方法

  首先,需要注意的是,若要通过 setter 方法来配置 bean ,那么这个 bean 里面一定要有 setter 方法,否则 Spring 会报错

  下面,我附上 XML 文件的代码

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!-- 添加 Address 和 Person --><bean id="address" class="com.spring.xmlBean.Address"><property name="city" value="日照"></property><property name="province" value="山东"></property></bean><bean id="person" class="com.spring.xmlBean.Person"><property name="name" value="Little-Koala"></property><property name="age" value="18"></property><!-- 通过 ref 引用了 address 这个 bean --><property name="address" ref="address"></property></bean>
</beans>
Spring Bean Configuration File

运行刚才测试用的那个 main 方法,发现配置成功了

在配置的时候,我们使用了 <property name="属性名"  value="值" ></property> 这个节点来对 bean 进行配置

其中,我们的 person 中有一个 Address 属性,它通过 ref 这个属性节点引用了 id 值为 address 的 bean

总结:通过 setter 方法来配置 bean ,我们使用 property 节点来进行配置,但前提是这个 bean 要有 setter 方法。其中,name 属性表示 bean 的属性名,bean 的属性值可以通过 value 属性来直接设置,也可以通过 ref 属性来引用其他的 bean

 

2. 通过构造器来进行配置

  首先要注意的问题,在配置之前要有自己的构造器。我们通过 <constructor-arg></constructor-arg> 这个节点来进行配置,下面附上代码:

<bean id="address" class="com.spring.xmlBean.Address"><constructor-arg name="city" value="日照"></constructor-arg><constructor-arg name="province" value="山东"></constructor-arg><!-- <property name="city" value="日照"></property><property name="province" value="山东"></property>-->
</bean>
Spring Bean Configuration File

上面的 Address 这个 bean 换成了用构造器来配置,运行的效果和上面是一样的

其中,name 代码构造器中属性的名字,value 代表值

 

刚才上面说了怎样配置 bean ,还没有具体的讲怎么样从容器中获取 bean

获取bean分两步:

  1. 创建 IOC 容器

  2. 从容器中获取 bean

下面附上代码:

package com.spring.test;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;import com.spring.helloworld.HelloWorld;
import com.spring.xmlBean.Person;public class TestMain {public static void main(String[] args) {// 创建 Spring 的 IOC 容器ApplicationContext ctx = new ClassPathXmlApplicationContext("beanConfiguration-xml.xml");// 使用 getBean() 方法, 通过传入刚才的 id 名,来获取 bean, 但是这里返回的是一个 Object 对象, 所以要转型Person person = (Person) ctx.getBean("person");// 打印 person
        System.out.println(person);}
}
怎样获取 Bean

这是刚才的那个测试类

其中 getBean( ) 方法可以通过传入 id 值来获取 IOC 容器中的 bean ,也可以通过传入 Bean.class 来获取对应类型的对象

 

以上内容都是基础的内容,还有一部分没有提到,剩下的那些内容在以后的学习中会慢慢接触,多读源码,多看文档,慢慢的就会了

转载于:https://www.cnblogs.com/zyx1301691180/p/7665971.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/428681.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

1195C. Basketball Exercise

C. Basketball Exercise&#xff1a;题目 经典简单dp&#xff0c;考虑前两天的就行#include <bits/stdc.h> using namespace std; typedef long long ll; vector<int> a((int)6e5); vector<int> b((int)6e5); ll dp[(int)5e5][3]; int main() {int n;cin>…

基于用户击键特征的身份鉴别系统

简单来说&#xff0c;我们要做的就是一种通过用户敲击键盘的习惯进行身份鉴别的系统。国内外之前有一些相关研究&#xff0c;但是通常是数千条数据训练&#xff0c;而且不能随意改变敲击的字符串&#xff0c;或者是有的要求采用带有压力传感器的键盘&#xff0c;难以实用和推广…

1350B. Orac and Models

B. Orac and Models&#xff1a;题目 题意&#xff1a;找一个最长的串&#xff0c;后一个下标可以整除前一个&#xff0c;并且a[i]<a[i1]#include <bits/stdc.h> using namespace std; typedef long long ll; vector<int> a((int)6e5); vector<int> b((i…

linux 配置EPEL源

配置EPEL源[rootansible ~]# rpm -Uvh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm [rootansible ~]# rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6 [rootansible ~]# yum install ansible -y #安装ansible转载于:https://www.cnblogs.c…

B. Mashmokh and ACM

414B. Mashmokh and ACM&#xff1a;题目 1400分就进入经典dp了 题意&#xff1a;给你1-n的数&#xff0c;构造一个长度为k的串&#xff0c;后一个数能整除前一个数#include <bits/stdc.h> using namespace std; #define int long long vector<int> a((int)6e5); …

最长不下降子序列 (O(nlogn)算法)

分析&#xff1a; 定义状态dp[i]表示长度为i的最长不下降子序列最大的那个数。 每次进来一个数直接找到dp数组第一个大于于它的数dp[x]&#xff0c;并把dp[x - 1]修改成 那个数。就可以了 AC代码&#xff1a; # include <iostream> # include <cstdio> # include &…

1380C. Create The Teams

C. Create The Teams&#xff1a;题目 正常人都会用dp吗&#xff1f;不应该是道贪心题吗&#xff1f;#include <bits/stdc.h> using namespace std; #define int long long vector<int> a((int)6e5); vector<int> b((int)6e5), c((int)6e5); const int mod …

【DOS】dos命令大全

net use ipipc$ " " /user:" " 建立IPC空链接net use ipipc$ "密码" /user:"用户名" 建立IPC非空链接net use h: ipc$ "密码" /user:"用户名" 直接登陆后映射对方C&#xff1a;到本地为H:net use h: ipc$ 登陆后映…

JS基础_break和continue

1 <!DOCTYPE html>2 <html>3 <head>4 <meta charset"UTF-8">5 <title></title>6 <script type"text/javascript">7 8 /*9 * break关键字可以…

538B. Quasi Binary

B. Quasi Binary&#xff1a;题目 这题目建议挪到1000分&#xff0c;它不配1400#include <bits/stdc.h> using namespace std; #define int long long vector<int> a((int)6e5); vector<int> b((int)6e5), c((int)6e5); const int mod 1e9 7; signed main…

289B. Polo the Penguin and Matrix

B. Polo the Penguin and Matrix&#xff1a;题目 思路&#xff1a;纯暴力#include <bits/stdc.h> using namespace std; // #define int long long vector<int> a((int)6e5); vector<int> b((int)6e5), c((int)6e5); const int mod 1e9 7; int g[111][11…

HDU 1525 类Bash博弈

给两数a,b&#xff0c;大的数b b - a*k,a*k为不大于b的数,重复过程&#xff0c;直到一个数为0时&#xff0c;此时当前操作人胜。 可以发现如果每次bb%a&#xff0c;那么GCD的步数决定了先手后手谁胜&#xff0c;而每次GCD的一步过程视为一个子游戏&#xff0c;但是可以发现如果…

HDU 3094 树上删边 NIM变形

基本的树上删边游戏 写过很多遍了 /** Date : 2017-10-13 18:19:37* FileName: HDU 3094 树上删边 NIM变形.cpp* Platform: Windows* Author : Lweleth (SoungEarlfgmail.com)* Link : https://github.com/* Version : $Id$*/ #include <bits/stdc.h> #define LL …

1320A. Journey Planning

A. Journey Planning&#xff1a;题目 mp的应用&#xff0c;和下标同样的差一定会越来越大&#xff0c;知道这点就好写了。#include <bits/stdc.h> using namespace std; #define int long long vector<int> a((int)6e5); vector<int> b((int)6e5), c((int)…

1245C. Constanze‘s Machine

C. Constanze’s Machine&#xff1a;题目 众所周知&#xff0c;斐波那契数列属于dp#include <bits/stdc.h> using namespace std; #define int long long vector<int> a((int)6e5); vector<int> b((int)6e5), c((int)6e5); const int mod 1e9 7; map<…

常见三种字符编码的区别:ASCII、Unicode、UTF-8

什么是字符编码&#xff1f; 计算机只能处理数字&#xff0c;如果要处理文本&#xff0c;就必须先把文本转换为数字才能处理。最早的计算机在设计时采用8个比特&#xff08;bit&#xff09;作为一个字节&#xff08;byte&#xff09;&#xff0c;所以&#xff0c;一个字节能表…

1108D. Diverse Garland

D. Diverse Garland&#xff1a;题目 什么脑瘫题目&#xff01;&#xff01;&#xff01;可恶&#xff0c;和dp有什么关系&#xff1f;但是强迫症让我不得不写&#xff0c;空一个很难受&#xff01;&#xff01;#include <bits/stdc.h> using namespace std; #define in…

Oracle存储过程procedure in、out、in out 模式参数【不发布,纯转】

Oracle存储过程procedure in、out、in out 模式参数 Oracle存储过程基本语法介绍 注意存过不会自动提交,需要在存过本身添加commit; rollback;等语句转载于:https://www.cnblogs.com/whatlonelytear/p/7680383.html

1451C. String Equality

C. String Equality&#xff1a;题目 我也不知道这算不算dp....虽然它有一个dp的标签#include <bits/stdc.h> using namespace std; #define int long long vector<int> a((int)6e5); vector<int> b((int)6e5), c((int)6e5); const int mod 1e9 7; int mp…

导航,头部,CSS基础

制作自己的导航条。HTML头部元素&#xff1a;<base> 定义了页面链接标签的默认链接地址<style> 定义了HTML文档的样式文件<link> 定义了一个文档和外部资源之间的关系练习样式表&#xff1a;行内样式表内嵌样式表外部样式表分别练习定义三类选择器&#x…