博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring中的Bean配置 (16)——在Spring的IOC容器里配置Bean(通过FactoryBean)——基于XML文件的方式
阅读量:3962 次
发布时间:2019-05-24

本文共 1509 字,大约阅读时间需要 5 分钟。

在这里插入图片描述

  • Spring 中有两种类型的 Bean, 一种是普通Bean, 另一种是工厂Bean, 即FactoryBean.
  • 工厂 Bean 跟普通Bean不同, **其返回的对象不是指定类的一个实例, 其返回的是该工厂 Bean 的 getObject 方法所返回的对象 **

下面是FactoryBean接口中的方法

在这里插入图片描述

演示:
Car_FactoryBean.java

package com.atguigu.spring.bean;import org.springframework.beans.factory.FactoryBean;//自定义的FactoryBean,需要实现FactoryBean的接口public class Car_FactoryBean implements FactoryBean
{
private String brand; public void setBrand(String brand) {
this.brand=brand; } //返回bean的对象 @Override public Car getObject() {
return new Car(brand, 80000); } //返回bean的类型 @Override public Class
getObjectType(){
return null; } @Override public boolean isSingleton() {
return false; }}

Car.java

package com.atguigu.spring.bean;public class Car {
private String brand; private double price; public Car(String brand, double price) {
super(); this.brand = brand; this.price = price; } @Override public String toString() {
return "Car [brand=" + brand + ", price=" + price + "]"; }}

application.xml

Main.java

package com.atguigu.spring.bean;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class Main {
public static void main(String[] args) {
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("application.xml"); Car car1=(Car) applicationContext.getBean("car1"); System.out.println(car1); }}

转载地址:http://qrozi.baihongyu.com/

你可能感兴趣的文章
C++实现http下载 && 24点计算编码风格
查看>>
memcached了解使用和常用命令详解
查看>>
GDB调试各功能总结
查看>>
"undefined reference to" 多种可能出现的问题解决方法
查看>>
类结构定义
查看>>
Windows下关于多线程类 CSemaphore,CMutex,CCriticalSection,CEvent,信号量CSemaphore的使用介绍
查看>>
图像处理基本算法(汇总)以及实现
查看>>
C++编程获取本机网卡信息 本机IP 包括Windows和Linux
查看>>
C++连接CTP接口实现简单量化交易
查看>>
服务端使用c++实现websocket协议解析及通信
查看>>
C# string.Format使用说明
查看>>
Linux下安装Mysql数据库开发环境
查看>>
Linux用户及用户组添加和删除操作
查看>>
通用 Makefile 的编写方法以及多目录 makefile 写法
查看>>
C++的4种智能指针剖析使用
查看>>
RPC框架实现之容灾策略
查看>>
Docker私库
查看>>
hdu——1106排序(重定向)
查看>>
hdu——1556Color the ball(树状数组)
查看>>
hdu——1541Stars(树状数组)
查看>>