day118 - 基于xml管理bean的入门案例

发布时间 2023-07-13 19:07:36作者: 北海之上

基于xml管理bean

入门案例

导入依赖

<dependencies>
    <!-- 基于Maven依赖传递性,导入spring-context依赖即可导入当前所需所有jar包 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.3.1</version>
    </dependency>
    <!-- junit测试 -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
</dependencies>

 

创建helloworld

package com.gu.spring.pojo;
​
public class HelloWorld {
    public void sayHello(){
        System.out.println("hello spring");
    }
}

 

配置spring

<!--
    bean: 将对象交给ioc容器管理
    属性:
    id:bean得唯一标识,不能重复
    class:设置bean对象所对应的类型
-->
    <bean id="helloworld" class="com.gu.spring.pojo.HelloWorld"></bean>

 

测试类

@Test
public void test(){
    //获取ioc容器
    ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
    //获取ioc容器中的bean对象
    HelloWorld helloworld = (HelloWorld) ioc.getBean("helloworld");
    helloworld.sayHello();
​
}

 

总结

通过测试类中创建ioc的容器对象,读取spring中的配置文件,文件中指定了自定义的组件类,ioc容器调用组件创建对象。

注意

Spring 底层默认通过反射技术调用组件类的无参构造器来创建组件对象,这一点需要注意。如果在需要无参构造器时,没有无参构造器,则会抛出下面的异常:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name'helloworld' defined in class path resource [applicationContext.xml]: Instantiation of bean failed; nested exception isorg.springframework.beans.BeanInstantiationException: Failedto instantiate [com.atguigu.spring.bean.HelloWorld]: No default constructor found; nestedexception is java.lang.NoSuchMethodException:com.atguigu.spring.bean.HelloWorld.()

over