怎么在Spring中利用xml文件配置Bean

发布时间:2021-05-25 16:36:26 作者:Leah
来源:亿速云 阅读:164

这篇文章将为大家详细讲解有关怎么在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());
  }

输出:

怎么在Spring中利用xml文件配置Bean

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

<constructor-arg index="0" type="java.lang.String">
      <value><![CDATA[<tom>]]></value>
    </constructor-arg>

关于怎么在Spring中利用xml文件配置Bean就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. 利用Spring怎么多去Bean本身的id
  2. Spring在xml文件中配置Bean的方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

spring xml bean

上一篇:怎么在springboot项目中访问静态资源

下一篇:如何在SpringBoot 中配置提示功能

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》