Spring IoC简介

一.基本概念:

控制反转:对象实例不再由调用者来创建,而是由容器(Spring)来创建,控制发生反转。

依赖注入:(Spring)容器负责将被依赖对象赋值给调用者的成员变量,,这就是依赖注入。

二.Spring IOC容器实例化对象

Spring IoC主要基于BeanFactory和ApplicationContext两个接口。

    1.BeanFactory接口

package test;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;

import dao.TestDao;

public class Test02 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
        BeanFactory beanfac=new XmlBeanFactory(new FileSystemResource("F:\\java_work\\spring01\\src\\applicationContext.xml"));
        //通过容器获取实例
        TestDao testdao=(TestDao) beanfac.getBean("it");
        testdao.sayHello();
	}

}

2.ApplicationContext接口

   ClassPathXmlApplicationContext创建

package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import dao.TestDao;

public class Test {
public static void main(String[] args) {
	//初始化spring容器ApplicationContext.加载配置文件
	ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
     //ApplicationContext  applicationContext=new ClassPathXmlApplicationContext("");
	TestDao td=(TestDao) ctx.getBean("it");
	td.sayHello();
}
}

   FileSystemXmlApplication创建

package test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import dao.TestDao;

public class filexml {

	public static void main(String[] args) {
	      ApplicationContext appContext=new FileSystemXmlApplicationContext("F:\\java_work\\spring01\\src\\applicationContext.xml");
	      TestDao test=(TestDao) appContext.getBean("it");
	      test.sayHello();
	}

}

通过web服务器实例化ApplicationContext容器

  <!-- 指定spring配置文件 -->
    <context-param>
     <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext-*.xml,classpath*:applicationContext-*.xml</param-value>
    </context-param>
  <!-- 配置核心监听器 -->
    <listener>
       <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

猜你喜欢

转载自blog.csdn.net/qq_32067151/article/details/82905795