博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring学习(4)IOC容器配置bean:定义与实例化
阅读量:6959 次
发布时间:2019-06-27

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

一.  IOC容器配置

  1. 一些概念

  (1)IOC容器

  定义:具有管理对象和管理对象之间的依赖关系的容器。

  作用:应用程序无需自己创建对象,对象由IOC容器创建并组装。BeanFactory是IOC容器的核心。

  流程:IOC容器根据配置文件,读取配置元数据,通过元数据库对程序中的各个对象进行实例化和装配。Spring与配置文件完全解耦,可以使用其他任何方式进行配置元数据,比如注解、基于java文件、基于属性文件的配置都可以。

  

 

  (2)Bean:IOC容器管理的应用程序的对象我们称它为bean。

  (3)IOC容器核心接口:org.springframework.beans.BeanFactory、org.springframework.context.ApplicationContext

  BeanFactory提供了IOC容器的最基本功能,ApplicationContext是BeanFactory的扩展,添加了更多的企业级功能的支持。

  XmlBeanFactory:BeanFactory的实现,可以从classpath或者文件系统获取资源,在Spring 4.0中已经不建议使用,直接使用applicationContext的实现类。

  ClassPathXmlApplicationContext、FileSystemXmlApplicationContext是ApplicationContext的实现,分别为从classpath、文件系统获取配置文件。

  例子:

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");        BeanFactory beanFactory = new ClassPathXmlApplicationContext("applicationContext.xml");

  

  2. Bean的配置

  (1)Spring IOC容器的目的就是管理bean,这些bean将根据配置文件中bean的定义进行创建,bean定义在容器内部由BeanDefintion对象表示,主要包含以下信息:

  ●全限定类名(FQN):用于定义Bean的实现类;(通过构造器和静态工厂方法进行实例化,必需属性。)

  ●Bean行为定义:这些定义了Bean在容器中的行为;包括作用域(单例、原型创建)、是否惰性初始化及生命周期等;

  ●Bean创建方式定义:说明是通过构造器还是工厂方法创建Bean;

  ●Bean之间关系定义:即对其他bean的引用,也就是依赖关系定义,这些引用bean也可以称之为同事bean 或依赖bean,也就是依赖注入。

  (2)Bean的命名:

  
  

  (3)Bean的实例化

  实例化:使用构造器(无参构造器和参数构造器)、静态工厂方法、实例工厂方法。

  静态工厂类与实例工厂类:

package self.springmvc.beanInstantiaton.service;import self.springmvc.beanInstantiaton.service.impl.HelloServiceImpl;import self.springmvc.beanInstantiaton.service.inter.HelloService;/** * Description */public class HelloServiceStaticFactory {    public static HelloService getBean(){        return new HelloServiceImpl();    }    public static HelloService getBean(String msg){        return new HelloServiceImpl(msg);    }}package self.springmvc.beanInstantiaton.service;import self.springmvc.beanInstantiaton.service.impl.HelloServiceImpl;import self.springmvc.beanInstantiaton.service.inter.HelloService;/** * Description */public class HelloServiceFactory {    public  HelloService getBean(){        return new HelloServiceImpl();    }    public  HelloService getBean(String msg){        return new HelloServiceImpl(msg);    }}

  

    

转载于:https://www.cnblogs.com/knsbyoo/p/9217324.html

你可能感兴趣的文章
Xamarin 免费了,你能做什么?
查看>>
JSP开发中对jstl的引用方式(标签库引用)
查看>>
php header 404写法 php header函数用法
查看>>
can't load package the specified module could not be found
查看>>
安装SQL Server2016正式版
查看>>
hiho_1138_island_travel
查看>>
一次tomcat服务器被入侵解决办法
查看>>
你必须知道的Microsoft SQL Server一
查看>>
IDEA新建MAVEN项目时速度缓慢
查看>>
使用Amoeba for mysql实现mysql读写分离
查看>>
WinIo驱动级键盘模拟编程
查看>>
python打印常见的图案
查看>>
《你不知道的JavaScript》整理(六)——强制类型转换
查看>>
HBase 常用Shell命令
查看>>
php设计模式——模板模式
查看>>
UITextField 基本设置
查看>>
HH生病了(hpu1136)
查看>>
赫夫曼树的构建、编码、译码解析
查看>>
tomcat管理员password设置
查看>>
【日志】修改redis日志路径
查看>>