-
什么是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 -
什么是控制反转(或依赖注入)
控制反转(IoC=Inversion of Control)IoC,用白话来讲,就是由容器控制程序之间的(依赖)关系,而非传统实现中,由程序代码直接操控。这也就是所谓“控制反转”的概念所在:(依赖)控制权由应用代码中转到了外部容器,控制权的转移,是所谓反转。
IoC还有一个另外的名字:“依赖注入 (DI=Dependency Injection)” ,即由容器动态的将某种依赖关系注入到组件之中
案例:实现Spring的IoCIOC/DI
将以前由程序员实例化对象/赋值的工作交给了spring处理 -
如何在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注1:struts2的Action请使用多例模式
-
简单属性的配置:
8+1+3
8基础数据+String+3个sql
java.util.Date
java.sql.Date
java.sql.Time
java.sql.Timestamp
通过标签赋值即可 -
复杂属性的配置
5.1 JavaBean
ref bean=""
5.2 List或数组
5.3 Map
5.4 Properties -
针对项目,配置文件路径的2种写法
ApplicationContext
String path = “applicationContext.xml”;
String path = “classpath:applicationContext-*.xml”;//src
String[] path = new String[] { “applicationContext-a.xml”, “applicationContext-b.xml” };//分模块开发 -
spring与web项目的集成
WEB项目如何读取spring上下文
通过监听器实现ServletContextListener
contextConfigLocation:classpath:applicationContext-*.xml -
log4j2
-
spring.pom
spring-context
spring-orm
spring-web
spring-aspects
注:创建spring的XML文件时,需要添加beans/aop/tx/context标签支持
简介
spring-context.xml
ioc(注意导包和Spring插件。导包导本地仓库即可,插件可百度。)
junit改为4.12版本
jar包:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
1、spring tool suite官方下载地址:http://spring.io/tools/sts/all
2、很详细的网文在线安装介绍:http://www.cnblogs.com/liuyungao/p/6213997
创建一个接口:
public interface UserBiz {
public void doSomething();
}
public class UserAction {
private UserBiz userBiz/*=new UserBizImpl2()*/;
public void aaa(){
this.userBiz.doSomething();
}
public void bbb(){
this.userBiz.doSomething();
}
public UserBiz getUserBiz() {
return userBiz;
}
public void setUserBiz(UserBiz userBiz) {
this.userBiz = userBiz;
}
}
public class TeaAction {
private UserBiz userBiz/*=new UserBizImpl()*/;
public void aaa(){
this.userBiz.doSomething();
}
public void bbb(){
this.userBiz.doSomething();
}
public UserBiz getUserBiz() {
return userBiz;
}
public void setUserBiz(UserBiz userBiz) {
this.userBiz = userBiz;
}
}
/**
* 模拟做项目实现某一功能
* @author Administrator
*
*/
public class UserBizImpl implements UserBiz{
/**
* 打个比方:
* 图片上传, inputstream、outputstream
* 做优化,bufferedreader、bufferedwrieam
*/
public void doSomething() {
System.out.println("实现方式一:只为完成功能,不考虑性能");
// System.out.println("系统升级,性能更优!");
}
}
/**
* 模拟做项目实现某一功能
* @author Administrator
*
*/
public class UserBizImpl2 implements UserBiz{
/**
* 打个比方:
* 图片上传, inputstream、outputstream
* 做优化,bufferedreader、bufferedwrieam
*/
public void doSomething() {
System.out.println("系统升级,性能更优!");
}
导入Spring插件之后,才有这个xml:
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<bean class="com.ioc.biz.impl.UserBizImpl" id="userBiz"></bean>
<bean class="com.ioc.biz.impl.UserBizImpl2" id="userBiz2"></bean>
<bean class="com.ioc.biz.web.UserAction" id="userAction">
<property name="userBiz" ref="userBiz"></property>
</bean>
<bean class="com.ioc.biz.web.TeaAction" id="teaAction">
<property name="userBiz" ref="userBiz2"></property>
</bean>
</beans>
public class IocTest {
@SuppressWarnings("resource")
public static void main(String[] args) {
//通过建模获取Spring的上下文,获取到了工程中的所有类
ApplicationContext applicationContext= new ClassPathXmlApplicationContext("spring-context.xml");
UserAction userAction = (UserAction) applicationContext.getBean("userAction");
userAction.aaa();
TeaAction teaAction = (TeaAction) applicationContext.getBean("teaAction");
teaAction.aaa();
}
set注入
基本数据类型注入
集合注入
对象注入
构造注入
基本数据类型注入
自动装配
//接口
public interface StuBiz {
public void doSomething();
}
public class StuBizImpl implements StuBiz {
public void doSomething() {
System.out.println("随便");
}
}
实体类:
public class StudentAction {
private Integer sid;
private String sname;
private List<String> hobbies;//在实际开发中,list里面放接口。
public StudentAction(){
}
public StudentAction(Integer sid, String sname) {
super();
this.sid = sid;
this.sname = sname;
}
//没有set/get方法是不能注入的。会报错: type of the setter match the return type of the getter
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public List<String> getHobbies() {
return hobbies;
}
public void setHobbies(List<String> hobbies) {
this.hobbies = hobbies;
}
public void aaa(){
System.out.println(this.sid + "," + this.sname + "," + this.hobbies);
}
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-context.xml加default-autowire=“byType”(注意看注释。是byType 就注释userBiz2 ):
这个图片下划红线是我改了路径的。
<bean class="com.zking.ioc.biz.web.StudentAction" id="stuAction">
<!-- set方法注入 -->
<!-- <property name="sid" value="1"></property> -->
<!-- <property name="sname" value="包子"></property> -->
<!-- 构造注入 -->
<constructor-arg name="sid" value="2"></constructor-arg>
<constructor-arg name="sname" value="叉烧包"></constructor-arg>
<property name="hobbies">
<list>
<value>吃肉包子</value>
<value>吃榨菜包</value>
</list>
</property>
</bean>
<!--Spring的新特性,自动装配 -->
<!--
byType:根据管理的javabean的接口属性,在spring的上下文中自动寻找实现类去注入,当找到两个及两个以上时会报错,
报错内容:available: expected single matching bean but found 2: userBiz,userBiz2
与Spring的上下文id无关
在公司一个接口有多个实现类
byName:根据管理的javabean中的接口名,在spring上下文中寻找 同名的id
进行注入。
-->
<bean class="com.ioc.biz.impl.StuBizImpl" id="stuBiz"></bean>
<bean class="com.ioc.biz.web.ClzAction" id="clzAction">
<!-- <property name="stuBiz" ref="stuBiz"></property> -->
<!-- <property name="userBiz" ref="userBiz"></property> -->
</bean>
IocTest加:
System.out.println("------------------------set/其他....注入------------------------");
StudentAction studentAction = (StudentAction) applicationContext.getBean("stuAction");
studentAction.aaa();
System.out.println("------------------------自动装配------------------------");
ClzAction clzAction = (ClzAction) applicationContext.getBean("clzAction");
clzAction.aaa();
tomcat整合ioc容器:
/**
* 将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);
}
public class UserServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
super.service(request, response);
System.out.println("do xxx");
//可以拿到IocTest类的任何一个Javabean
ApplicationContext applicationContext = SpringWebUtil.getApplicationContext(request.getServletContext());
ClzAction clzAction = (ClzAction) applicationContext.getBean("clzAction");
clzAction.aaa();
}
}
public class SpringLoaderListener implements ServletContextListener {
// private String configLocation="xxx";
//监听,一旦写了,就会在tomcat启动的时候调用这个方法
public void contextInitialized(ServletContextEvent sce) {
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("springXml--"+springXml);
//注: 如果不喜欢spring-context.xml这个名字,想自己改给名字。即上面注释和web.xml的注释,去掉注释即可!
ApplicationContext applicationContext= new ClassPathXmlApplicationContext("spring-context.xml");
SpringWebUtil.setApplicationContext(applicationContext, servletContext);
}
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.ioc.listener.SpringLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>userServlet</servlet-name>
<servlet-class>com.ioc.web.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>userServlet</servlet-name>
<url-pattern>/userServlet</url-pattern>
</servlet-mapping>
</web-app>