Spring:ioc

1. 什么是spring,它能够做什么?
 

 Spring是一个开源框架,它由Rod Johnson创建。它是为了解决企业应用开发的复杂性而创建的。

 Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情。然而,Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java应用都可以从Spring中受益。

   目的:解决企业应用开发的复杂性
   功能:使用基本的JavaBean代替EJB,并提供了更多的企业应用功能
   范围:任何Java应用

   简单来说,Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架。

   1.1 中间层框架、万能胶
       struts2
       spring
       hibernate
   1.2 容器框架
         JavaBean    项目中的一个个类
         IOC和AOP

2. 什么是控制反转(或依赖注入) 

控制反转(IoC=Inversion of Control)IoC,用白话来讲,就是由容器控制程序之间的(依赖)关系,而非传统实现中,由程序代码直接操控。这也就是所谓“控制反转”的概念所在:(依赖)控制权由应用代码中转到了外部容器,控制权的转移,是所谓反转。

IoC还有一个另外的名字:“依赖注入(DI=Dependency Injection)”  ,即由容器动态的将某种依赖关系注入到组件之中 
   案例:实现Spring的IoC

   IOC/DI
     将以前由程序员实例化对象/赋值的工作交给了spring处理

2.1

//User接口

package com.zking.ioc.biz;

public interface UserBiz {
	public void doSomething();
}




//User实现类

package com.zking.ioc.biz.impl;

import com.zking.ioc.biz.UserBiz;

/**
 * 模拟做项目实现某一功能
 * @author Administrator
 *
 */
public class UserBizImpl implements UserBiz{
/**
 * 图片上传	inputStream	outputstream
 * 做优化		bufferedreader	bufferedwriter
 */
	public void doSomething() {
		// TODO Auto-generated method stub
		System.out.println("实现方法一:只为完成功能,不考虑性能");
	}
	
}





//假设进行了优化
package com.zking.ioc.biz.impl;

import com.zking.ioc.biz.UserBiz;

/**
 * 模拟做项目实现某一功能
 * @author Administrator
 *
 */
public class UserBizImpl2 implements UserBiz{
/**
 * 图片上传	inputStream	outputstream
 * 做优化		bufferedreader	bufferedwriter
 */
	public void doSomething() {
		// TODO Auto-generated method stub
		System.out.println("系统升级:性能更优化");
	}
	
}






//UserAction


package com.zking.ioc.web;

import com.zking.ioc.biz.UserBiz;
import com.zking.ioc.biz.impl.UserBizImpl;
import com.zking.ioc.biz.impl.UserBizImpl2;

public class UserAction {
	/**
	 * 如果要进行调优的话,用了几个就要改几个,比较麻烦
	 * 运用spring进行调优,只需要改配置注入就可以了,就不需要new一个类了。
	 */
//	private UserBiz userBiz=new UserBizImpl();
	private UserBiz userBiz;
	
	
	
	public UserBiz getUserBiz() {
		return userBiz;
	}

	public void setUserBiz(UserBiz userBiz) {
		this.userBiz = userBiz; 
	}

	public void aaa() {
		this.userBiz.doSomething();
	}
	
	public void bbb() {
		this.userBiz.doSomething();
	}
}


2.2、安装spring插件

2.2.1、spring tool suite官方下载地址:http://spring.io/tools/sts/all(注:如果提供了解压包的话,解压文件)

很详细的网文在线安装介绍:http://www.cnblogs.com/liuyungao/p/6213997

2.2.2、点击Help下的install New Software

选择spring插件的安装路径

可以不选中Contact all update sites during

选中这四个选项,点击下一步,完成之后会弹出一个框,全部勾选,重启eclipse

2.3、创建spring-context.xml,点击下一步

注:spring-context.xml文件放在src/main/resources里

2.4、配置

<!-- 讲解ioc的用途 -->
<bean class="com.zking.ioc.biz.impl.UserBizImpl" id="userBiz2"></bean>
<bean class="com.zking.ioc.biz.impl.UserBizImpl2" id="userBiz"></bean>
<bean class="com.zking.ioc.web.UserAction" id="userAction">
	<property name="userBiz" ref="userBiz"></property><!--注入-->
</bean>
<bean class="com.zking.ioc.web.TeaAction" id="teaAction">
	<property name="userBiz" ref="userBiz"></property>
</bean>


3. 如何在spring当中定义和配置一个JavaBean(使用无参构造方法+set方法创建一个JavaBean)


   3.1 id:在容器中查找Bean的id(唯一、且不能以/开头)
   3.2 class:bean的完整类名
   3.3 name:在容器中查找Bean的名字(唯一、允许以/开头、允许多个值,多个值之间用逗号或空格隔开)
   3.4 scope:(singleton|prototype)默认是singleton
   3.4.1 singleton(单例模式):在每个Spring IoC容器中一个bean定义对应一个对象实例
   3.4.2 prototype(原型模式/多例模式):一个bean定义对应多个对象实例
   3.4 abstract:将一个bean定义成抽象bean(抽象bean是不能实例化的),抽象类一定要定义成抽象bean,非抽象类也可以定义成抽象bean
   3.5 parent:指定一个父bean(必须要有继承关系才行)
   3.6 init-method:指定bean的初始化方法
   3.7 constructor-arg:使用有参数构造方法创建javaBean

//Student接口
package com.zking.ioc.biz;

public interface StuBiz {
	public void doSomething();
}






//Student实现类
package com.zking.ioc.biz.impl;

import com.zking.ioc.biz.StuBiz;

public class StuBizImpl implements StuBiz {

	public void doSomething() {
		// TODO Auto-generated method stub
		System.out.println("啊哈哈");
	}
	
}






//StudentAction
package com.zking.ioc.web;

import java.util.List;

public class StudentAction {
	private Integer sid;
	private String sname;
	private List<String> hobby;
	
	public List<String> getHobby() {
		return hobby;
	}
	public void setHobby(List<String> hobby) {
		this.hobby = hobby;
	}
	public StudentAction() {
		super();
	}
	public StudentAction(Integer sid, String sname) {
		super();
		this.sid = sid;
		this.sname = sname;
	}
	
	public void aaa() {
		System.out.println(this.sid+"," +this.sname+","+this.hobby);
	}
}

 IOC注入的类型,以及方式

<!-- 讲解IOC注入的类型,以及方式 -->
<bean class="com.zking.ioc.web.StudentAction" id="stuAction">
<!--set方法注入  -->
	<!-- <property name="sid" value="22"></property>
	<property name="sname" value="胖子"></property> -->
	<constructor-arg name="sid" value="22"></constructor-arg>

<!--构造方法注入  -->
	<constructor-arg name="sname" value="黑黑"></constructor-arg>
	<property name="hobby">
		<list>
			<value>喝冬瓜</value>
			<value>donggua</value>
		</list>
	</property>
</bean>

4. 简单属性的配置:


   8+1+3
   8基础数据+String+3个sql
   java.util.Date
     java.sql.Date
     java.sql.Time
     java.sql.Timestamp
   通过<value>标签赋值即可


5. 复杂属性的配置


  5.1 JavaBean
      ref bean=""
  5.2 List或数组
  5.3 Map
  5.4 Properties


6. 针对项目,配置文件路径的2种写法


   ApplicationContext
   String path = "applicationContext.xml";
   String path = "classpath:applicationContext-*.xml";//src
   String[] path = new String[] { "applicationContext-a.xml", "applicationContext-b.xml" };//分模块开发


7. spring与web项目的集成

   WEB项目如何读取spring上下文


   通过监听器实现ServletContextListener


   contextConfigLocation:classpath:applicationContext-*.xml

8. log4j2
  


9. spring.pom
   spring-context
   spring-orm
   spring-web
   spring-aspects
   注:创建spring的XML文件时,需要添加beans/aop/tx/context标签支持
   
   
简介
spring-context.xml
ioc
    set注入
        基本数据类型注入
        集合注入
        对象注入
    构造注入
        基本数据类型注入
    自动装配

注:用了自动装配就可以不用注入接口属性了
        default-autowire="byName"

package com.zking.ioc.web;

import com.zking.ioc.biz.StuBiz;
import com.zking.ioc.biz.UserBiz;

public class ClzAction {
	private UserBiz userBiz;
	private StuBiz stuBiz;
	public UserBiz getUserBiz() {
		return userBiz;
	}
	public void setUserBiz(UserBiz userBiz) {
		this.userBiz = userBiz;
	}
	public StuBiz getStuBiz() {
		return stuBiz;
	}
	public void setStuBiz(StuBiz stuBiz) {
		this.stuBiz = stuBiz;
	}
	
	public void aaa() {
		this.userBiz.doSomething();
		this.stuBiz.doSomething();
	}
}
<!--spring的新特性,自动装配  -->
<!--
	byType:根据管理的Javabean的接口的属性,在spring的上下文中自动寻找实现类去注入,当找到两个及两个以上时会报错,与spring的上下文id无关
	byName:根据管理的Javabean中的接口名,在spring上下文中去寻找同名的id进行注入
  -->
<bean class="com.zking.ioc.biz.impl.StuBizImpl" id="stuBiz"></bean>
<bean class="com.zking.ioc.web.ClzAction" id="clzAction">
<!-- <property name="stuBiz" ref="stuBiz"></property>
	<property name="userBiz" ref="userBiz"></property> -->

tomcat整合ioc容器

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>4.3.10.RELEASE</version>
</dependency>

//SpringWebUtil

package com.zking.ioc.util;

import javax.servlet.ServletContext;

import org.springframework.context.ApplicationContext;

/**
 * 将spring的上下文整合进Tomcat容器中
 * @author Administrator
 *
 */
public class SpringWebUtil {
	static String SPRING_CONTEXT_KEY="spring_context_key";
	/**
	 * spring的上下文放入Tomcat容器中
	 * @param applicationContext	已经建模好的spring的上下文
	 * @param servletContext	Tomcat上下文
	 */
	public static void setApplicationContext(ApplicationContext applicationContext,ServletContext servletContext) {
		servletContext.setAttribute(SPRING_CONTEXT_KEY,applicationContext );
	}
	
	public static ApplicationContext getApplicationContext(ServletContext servletContext) {
		return (ApplicationContext) servletContext.getAttribute(SPRING_CONTEXT_KEY);
	}
}

//SpringLaderListener

package com.zking.ioc.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

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

import com.zking.ioc.util.SpringWebUtil;

public class SpringLoaderListener implements ServletContextListener {
	
	private String configLocation="xxx";
	
	public void contextInitialized(ServletContextEvent sce) {
		// TODO Auto-generated method stub
		System.out.println("contextInitialized==============================");
		ServletContext servletContext=sce.getServletContext();
		String springXml="spring-context.xml";
		String path = servletContext.getInitParameter(configLocation);
		if(!(null==path||"".equals(path))) {
			springXml=path;
		}
		System.out.println("springXmlg--"+springXml);
		ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring-context.xml");
		SpringWebUtil.setApplicationContext(applicationContext, servletContext);
	}
	
}

//UserServlet

package com.zking.ioc.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;

import com.zking.ioc.util.SpringWebUtil;

public class UserServlet extends HttpServlet{
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.service(req, resp);
		System.out.println("do xxxx");
		ApplicationContext applicationContext = SpringWebUtil.getApplicationContext(req.getServletContext());
		ClzAction clzAction= (ClzAction) applicationContext.getBean("clzAction");
		clzAction.aaa();
	}
}

web.xml 

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <!-- <context-param>
  	<param-name>xxx</param-name>
  	<param-value>spring-xxx.xml</param-value>
  </context-param> -->
  <listener>
  	<listener-class>com.zking.ioc.listener.SpringLoaderListener</listener-class>
  </listener>
  <servlet>
  	<servlet-name>userServlet</servlet-name>
  	<servlet-class>com.zking.ioc.web.UserServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>userServlet</servlet-name>
  	<url-pattern>/userServlet</url-pattern>
  </servlet-mapping>
</web-app>


 

猜你喜欢

转载自blog.csdn.net/x_b_z123/article/details/83685413