第二章 创建Bean的方法及Bean范围

本文通过水果类比,探讨了Spring框架如何实例化配置文件中定义的对象,包括使用构造方法和工厂方法两种方式,并详细解释了当配置文件指定的类没有默认构造方法时可能遇到的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring是怎么来实例化配置文件中配置的对象呢?

 

构造方法:

以水果为例子:

水果接口

public interface Fruit {

     public void eat();

}

 

苹果实现类:

public class Apple implements Fruit {

     public void eat() {

         System.out.println("吃苹果");

     }

}

 

配置文件:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"

     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

     <bean id="fruit" class="model.Apple" />

</beans>

 

Test:

public class Test {

     public static void main(String[] args) {

         ApplicationContext act = new ClassPathXmlApplicationContext("applicationContext.xml");

         Fruit fruit = (Fruit)act.getBean("fruit");

         fruit.eat();

     }

}

这个时候我们可以看到可以成功运行, 接着我们修改苹果类:

public class Apple implements Fruit {

     private String name;

 

     public Apple(String name) {

         super();

         this.name = name;

     }

 

     public void eat() {

         System.out.println("吃苹果");

     }

}

给苹果类添加了一个属性,和一个有参的构造方法,请再次运行Test文件,可以看到以下异常:

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fruit' defined in class path resource [applicationContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [model.Apple]: No default constructor found; nested exception is java.lang.NoSuchMethodException: model.Apple.<init>()

注意看: BeanCreationException 创建失败异常

No default constructor found:默认的构造没有找到

 

工厂方法:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值