spring简介
spring简介
Spring 是于 2003 年兴起的一个轻量级的Java 开发框架,创始人是Rod Johnson,它是为了解决企业应用开发的复杂性而创建的,随着时代的发展,spring旗下发展了很多项目,并且越来越多的开发者开始使用这些项目。spring的优点如下:
- 方便解耦,简化开发(高内聚低耦合),可以将对象依赖关系的维护交给Spring管理。
- IOC(Inversion of Control)控制反转,对象的创建由spring完成,并将创建好的对象注入给使用者。
- AOP(Aspect Orient Programming)编程的支持,面向切面编程,可以将一些日志,事务等操作从业务逻辑的代码中抽取出来,这样子业务逻辑代码就更加纯净了,并且可以增强日志和事务复用性。
- 声明式事务的支持,只需要通过配置就可以完成对事务的管理,而无需手动编程。
- 方便集成各种优秀框架,其内部提供了对很多优秀框架(如:Struts、Hibernate、MyBatis等)的直接支持。
- 非侵入式,spring的api不会在业务逻辑的代码中出现,倘若有一天项目不使用spring了,那么可以很方便的移植到其他框架上。
第一个spring程序
添加依赖jar包
咱们这里使用spring 5.x的版本,要使用该版本的话,需要保证你的jdk是8以上。
要想使用spring框架的话,需要添加相关的jar包,在你的pom.xml文件中添加下面依赖即可:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
添加上面依赖之后,maven会将spring相关的一系列jar包下载到你的本地maven仓库中,这里会用到junit,所以不要把junit的依赖删除。
创建接口和实现类
创建一个接口和该接口的实现类:
package com.monkey1024.service;
public interface StudentService {
void study();
}
实现类:
package com.monkey1024.service.impl;
import com.monkey1024.service.StudentService;
public class StudentServiceImpl implements StudentService {
@Override
public void study() {
System.out.println("好好学习天天向上");
}
}
添加spring的配置文件
在maven项目的resources目录下添加spring配置文件,文件名可以随意命名,这里命名为:applicationContext.xml
里面需要添加一些xsd,拷贝下面的即可。
<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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="studentService" class="com.monkey1024.service.impl.StudentServiceImpl"/>
</beans>
在该spring配置文件中添加bean标签:
- id:该属性是Bean的唯一标识,java程序通过id访问该Bean。
- class:指定该Bean所属的类,这里只能是类,不能是接口。
创建测试类进行测试
想要使用StudentService的话,需要开发者自己手动通过new关键字创建该接口实现类的对象。虽然使用了接口可以实现程序的解耦,但是实际上在代码中还是有new StudentServiceImpl的语句,这个地方还是存在一些耦合的。
使用spring之后,在代码中通过spring获取StudentServiceImpl对象,这样子就去掉了之前代码中的耦合。
package com.monkey1024.test;
import com.monkey1024.service.StudentService;
import com.monkey1024.service.impl.StudentServiceImpl;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test01 {
/**
* 以前的写法:手动创建对象
*/
@Test
public void oldType(){
StudentService studentService = new StudentServiceImpl();
studentService.study();
}
/**
* 使用spring之后的写法:直接通过spring获取对象
*/
@Test
public void springType() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//从spring中获取对象
StudentService studentService = (StudentService) context.getBean("studentService");
studentService.study();
}
}
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.monkey1024</groupId>
<artifactId>01_firstspring</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>01_firstspring</finalName>
<plugins>
<!-- 编译插件,指定编译用的的jdk版本 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<!-- jdk的版本号 -->
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>secondmvc</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
applicationContext.xml
<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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 默认方式,需要保证该bean中有无参的构造方法 -->
<!-- scope有单态模式和原型模式,单态模式创建的对象是同一个对象 -->
<!-- id不能重复,class只能是类 -->
<bean id="studentService" init-method="init" destroy-method="destroy" class="com.monkey1024.service.impl.StudentServiceImpl"/>
<!--<bean id="studentService" scope="prototype" class="com.monkey1024.service.impl.StudentServiceImpl"/> -->
<!-- <bean id="studentService" class="com.monkey1024.service.impl.StudentServiceImpl"/> -->
<!-- bean后处理器 -->
<!-- <bean id="myBeanPostProcesser" class="com.monkey1024.proxy.MyBeanPostProcesser"/>-->
<!-- 实例工厂 -->
<!-- <bean id="myFactory" class="com.monkey1024.factory.MyBeanFactory"/> -->
<!-- <bean id="studentService" factory-bean="myFactory" factory-method="createStudentService"/> -->
<!-- 静态工厂 -->
<!-- <bean id="studentService" class="com.monkey1024.factory.MyBeanStaticFactory" factory-method="createStudentService"/> -->
</beans>
Test01
package com.monkey1024.test;
import org.junit.Test;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;
import com.monkey1024.service.StudentService;
import com.monkey1024.service.impl.StudentServiceImpl;
public class Test01 {
/*
* 以前的写法,手动创建对象
*/
@Test
public void oldType(){
StudentServiceImpl studentService = new StudentServiceImpl();
studentService.study();
}
@Test
public void newType(){
//读取spring配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
StudentService studentService = (StudentService) context.getBean("studentService");
// StudentService studentService1 = (StudentService) context.getBean("studentService");
// studentService.study();
System.out.println(studentService);
// System.out.println(studentService1);
// System.out.println(studentService==studentService1);
}
@Test
public void beanFactory(){
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
reader.loadBeanDefinitions(new FileSystemResource("G:\\JavaWeb\\01_firstspring\\src\\main\\resources\\applicationContext.xml"));
//当使用该bean的时候才会创建对象
StudentService studentService = (StudentService) factory.getBean("studentService");
}
@Test
public void initAndDestroy(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
StudentService studentService = (StudentService)context.getBean("studentService");
studentService.study();
((ClassPathXmlApplicationContext)context).close();
}
}
StudentService.java
package com.monkey1024.service;
public interface StudentService {
void study();
}
StudaentServiceImpl.java
package com.monkey1024.service.impl;
import com.monkey1024.service.StudentService;
public class StudentServiceImpl implements StudentService{
public void study(){
System.out.println("好好学习,天天向上");
}
public StudentServiceImpl(){
System.out.println("studentService构造方法的执行");
}
public void init(){
System.out.println("初始化方法");
}
public void destroy(){
System.out.println("销毁方法");
}
}
MyBeanPostProcesser.java
package com.monkey1024.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
/*
* 自定义bean后处理器,需要实现BeanPostProcessor
*/
public class MyBeanPostProcessor implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean,String beanName) throws BeansException{
System.out.println("执行before");
// 这里要将bean返回
return bean;
}
public Object postProcessAfterInitialization(Object bean,String beanName) throws BeansException{
if("studentService".equals(beanName)){
//创建InvocationHandler对象
InvocationHandler invocationHandler = ((Object p,Method method,Object[] args)->{
//调用study方法时使用动态代理对其进行增强
if("study".equals(method.getName())){
System.out.println("======目标方法开始=====");
//执行目标方法
Object result = method.invoke(bean,args);
System.out.println("======目标方法结束=====");
return result;
}
return method.invoke(bean, args);
});
//增强bean
Object proxy = Proxy.newProxyInstance(bean.getClass().getClassLoader(),
bean.getClass().getInterfaces()
, invocationHandler);
System.out.println("after方法的执行");
return proxy;
}
return bean;
}
}
MyBeanFactory.java
package com.monkey1024.factory;
import com.monkey1024.service.StudentService;
import com.monkey1024.service.impl.StudentServiceImpl;
/*
* 实例工厂
*/
public class MyBeanFactory {
public StudentService createStudentService(){
return new StudentServiceImpl();
}
}
MyBeanStaticFactory.java
package com.monkey1024.factory;
import com.monkey1024.service.StudentService;
import com.monkey1024.service.impl.StudentServiceImpl;
/*
* 静态工厂
*/
public class MyBeanStaticFactory {
public static StudentService createStudentService(){
return new StudentServiceImpl();
}
}