Spring
1、spring简介
spring框架,可以解决对象创建以及对象之间依赖关系的一种框架(容器)。
且可以和其他框架一起使用;Spring与Struts, Spring与hibernate
(起到整合(粘合)作用的一个框架)
Spring提供了一站式解决方案:s
1) Spring Core spring的核心功能: IOC容器, 解决对象创建及依赖关系
2) Spring Web Spring对web模块的支持。
可以与struts整合,让struts的action创建交给spring
spring mvc模式
3) Spring DAO Spring 对jdbc操作的支持 【JdbcTemplate模板工具类】
4) Spring ORM spring对orm的支持:
既可以与hibernate整合,【session】
也可以使用spring的对hibernate操作的封装
5)Spring AOP 切面编程
6)SpringEE spring 对javaEE其他模块的支持
2、环境搭建
2.1 maven依赖
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
</dependencies>
2.2 控制反转
控制翻转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式,在Spring中实现控制反转的是IoC容器,其实现方式是依赖注入(Dependency Injection)
明确 ioc 的作用: 削减计算机程序的耦合(解除我们代码中的依赖关系)。
讲人话就是:需要对象不用自己手动去创建,Spring帮你来创建,管理,装配。
当需要修改时,只需要修改beans.xml中标签的属性值,不用去修改代码。
2.2.1 第一个spring程序
1.实体类Hello
public class Hello {
private String str;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
public String toString() {
return "Hello{" +
"str='" + str + '\'' +
'}';
}
}
2.配置文件beans.xml:其中bean标签中的id值相当于对象名,class的值表示要new的类,property标签表示给对象中的属性property设置一个值value。
如果property的值的类型是一个对象,可以使用ref,表示引用spring容器中创建好的对象
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="hello" class="pojo.Hello">
<property name="str" value="Hello Spring"/>
</bean>
</beans>
**3.测试类:**ApplicationContext context = new ClassPathXmlApplicationContext(“beans.xml”);这句话表示拿到spring容器,然后用context.getBean(“id”)来获取对象,而不用去new了
public class MyTest {
public static void main(String[] args) {
//输入new CPX ,按alter+enter快捷生成
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello.toString());
}
}
2.3 IoC创建对象的方式
1.默认使用无参构造方法创建对象
2.当使用有参构造时,有三种方法
在配置文件加载的时候,容器中管理的对象就已经初始化了
3.依赖注入(重点)
依赖:bean对象的创建依赖于容器!
注入:bean对象中的所有属性,由容器来注入!
3.1 构造器注入
//实体类
public class User{
public User(String name){
this.name=name;
}
//get(),set(),toString()省略
}
通过参数下标:一个参数的下标为0
<bean id="user" class="pojo.User">
<constructor-arg index="0" value="zhongliwen"/>
</bean>
通过参数类型(多个参数相同类型会出问题,不建议使用)
<bean id="user" class="pojo.User">
<constructor-arg type="java.lang.String" value="zhongliwen"/>
</bean>
通过参数名(建议使用)
<bean id="user" class="pojo.User">
<constructor-arg name="name" value="zhongliwen"/>
</bean>
name:用于给构造函数的指定参数名赋值
ref:用于引用指定其它类型bean数据,值为其指定bean的id
3.2 set方式注入(重点)
实体类Student
private String name;
private Address address; //Address为一个类,里面一些属性
private String[] books;
private List<String> hobbies;
private Map<String,String> card;
private Set<String> games;
private Properties info;
private String wife;
配置文件beans.xml(重点)
name:用于调用set对应的方法名称(参数对应的set方法)
ref:用于引用指定其它类型bean数据,值为其指定bean的id
value:给属性赋值是基本数据类型和 string 类型的
//注册Address实体类
<bean id="addr" class="pojo/Address"/>
//注册Student实体类
<bean id="student" class="pojo/Student">
<property name="name" value="Lewis"/>//普通值,用value
<property name="address" ref="addr"/>//对象,用ref,与上面的地址bean的id值相同
<property name="books"> //数组注入
<array>
<value>红楼梦</value>
<value>西游记</value>
<value>三国演义</value>
</array>
</property>
<property name="hobbies"> //List注入
<list>
<value>听歌</value>
<value>敲代码</value>
<value>看电影</value>
</list>
</property>
<property name="card"> //Map注入
<map>
<entry key="身份证" value="4306XXXXXXXX"/>
<entry key="银行卡" value="1903XXXXXXXX"/>
</map>
</property>
<property name="games"> //Set注入
<set>
<value>LOL</value>
<value>DNF</value>
<value>CS</value>
</set>
</property>
<property name="info"> //properties资源文件注入
<props>
<prop key="url">jdbc:mysql://localhost:3306</prop>
<prop key="name">root</prop>
<prop key="password">123456</prop>
</props>
</property> //null注入
<property name="wife">
<null/>
</property>
3.3 C、P命名空间注入(了解)
首先需要在beans.xml文件下的beans标签中导入C、P的XML约束
xmls:c="http://www.springframework.org/schema/c"
xmls:p="http://www.springframework.org/schema/p"
<bean id="user" class="pojo/User" c:name="Lewis"/>
<bean id="user" class="pojo/User" p:name="Lewis"/>
其中,C对应有参构造,P对应set注入,是他们的简化版
4.Bean
作用: 用于配置对象让 spring 来创建的。
默认情况下它调用的是类中的无参构造函数。如果没有无参构造函数则不能创建成功。
属性:
id:给对象在容器中提供一个唯一标识。用于获取对象。
class:指定类的全限定类名。用于反射创建对象。默认情况下调用无参构造函数。
scope:指定对象的作用范围。
- singleton :默认值,单例的.
- prototype :多例的.
- request :WEB 项目中,Spring 创建一个 Bean 的对象,将对象存入到 request 域中.
- session :WEB 项目中,Spring 创建一个 Bean 的对象,将对象存入到 session 域中.
- global session :WEB 项目中,应用在 Portlet 环境.如果没有 Portlet 环境那么 globalSession 相当于 session.
- init-method:指定类中的初始化方法名称。 destroy-method:指定类中销毁方法名称。
通过配置文件给 bean 中的属性传值:使用 set 方法的方式
涉及的标签:
property属性:
name:找的是类中 set 方法后面的部分,用于给构造函数的指定参数名赋值
ref:用于引用指定其它类型bean数据,值为其指定bean的id
value:给属性赋值是基本数据类型和 string 类型的
4.1 bean的作用域
1.单例模式:
Spring默认机制,一个类只实例化一次,通过get方法得到的对象,即使对象的名字不同,本质还是同一个
2.原型模式:
每次从容器中get时,都会产生一个新对象!适用于多线程
3.其余的request,session,application,只能在web开发中使用到,表示对象的生存周期
单例对象:scope=”singleton”
一个应用只有一个对象的实例。
它的作用范围就是整个引用。
生命周期: 对象出生:当应用加载,创建容器时,对象就被创建了。
对象活着:只要容器在,对象一直活着。 对象死亡:当应用卸载,销毁容器时,对象就被销毁了。
多例对象:scope=”prototype”
每次访问对象时,都会重新创建对象实例。
生命周期: 对象出生:当使用对象时,创建新的对象实例。
对象活着:只要对象在使用中,就一直活着。
对象死亡:当对象长时间不用时,被 java 的垃圾回收器回收了。
4.2 bean的自动装配
实体类People,有两个宠物Cat,Dog
public class People{
private String name;
private Cat cat; //猫,狗的实体类省略,知道是一个对象类型就行
private Dog dog;
//setDog(),setCat(),getDog(),getCat(),toString()方法省略
}
byName自动装配:会自动在容器上下文中查找和people对象set方法后面的值对应的bean的id。如People实体类中有一个setDog方法,且beans.xml文件中有一个id值为dog的bean,因此people bean中可以省略dog的property,会自动注入。
简单来说就是:实体类有setDog方法,beans.xml中有id=”dog”的bean,省略dog property
<bean id="cat" class="pojo/Cat"/>
<bean id="dog" class="pojo/Dog"/>
<bean id="people" class="pojo/People" autowire="byName">
<property name="name" value="Lewis"/>
//<property name="cat" ref="cat"/>自动装配会自动完成,这两行代码可以省略
//<property name="dog" ref="dog"/>
</bean>
byType自动装配:自动在容器中查找和自己对象类型相同的bean(同一个pojo中)
小结:
byName的时候,需要保证所有bean的id唯一,并且这个id要和自动注入的属性的set方法的值一致!
byType的时候,需要保证所有的bean的class唯一,并且这个bean的属性要和自动注入的属性类型一致!
5 注解开发
1.在xml配置文件中的beans标签中加入注解支持
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/context
http://www.springframework.org/schema/context/spring-context.xsd"
2.开启注解支持
><context:annotation-config/> ><context:component-scan base-package="pojo"/>
3.注解使用:自动装配
用于创建对象的:他们的功能和xml配置文件中的bean标签是一样的
@Component:对整个类进行装配。所有属性不用写get/set方法。 属性: value:指定 bean 的 id。如 果不指定 value 属性,默认 bean 的 id 是当前类的类名。首字母小写。
@Controller:一般用于表现层的注解。
@Service:一般用于业务层的注解。
@Repository:一般用于持久层的注解
用于注入数据的:和xml配置文件中的property标签功能一样
@Autowired:自动按照类型注入:先通过类型,再通过名字,用在对象属性上。
可以使用在变量和方法上。当使用注解注入属性时,set 方法可以省略。它只能注入其他 bean 类型。当 有多个 类型匹配时,使用要注入的对象变量名称作为 bean 的 id,在 spring 容器查找,找到了也可以注 入成功。找不到 就报错。
**@Qualifier:**作用:在按照类中注入的基础之上再按照名称注入。给类名称注入时不能单独使用(必须与 Autowired配合)。 value值用于指定bean的id
@Resource:先通过名字,再通过类型,用在对象属性上。作用: 直接按照 Bean 的 id 注入。它也只能注 入其他 bean 类型。
以上三个注解都只能注入其它类型的bean类型的数据,而基本类型和String类型无法使用上述注解注入。集合类型只能通过xml配置
@Value:用于基本类型和String类型的注入,它可以使用spring中SpEL(也就是spring的el表达式)
SpEL的写法:${表达式}
用于改变作用范围的:和xml配置文件中的scope属性一致
@Scope: 用于指定bean的作用范围,属性:value:指定范围的取值,常用取值有:singleton、prototy
分别对应单例,和多例。默认值为单例
和生命周期相关的:
@PreDestroy: 用于指定销毁方法
@PostConstruct: 用于指定初始化方法
@Configuration : 用于指定当前类是一个 spring 配置类,当创建容器时会从该类上加载注解。获取容器时需要使用 AnnotationApplicationContext(有@Configuration 注解的类.class)。 属性: value:用于指定配置类的字节码
小结:
- XML更加万能,适用于任何场合,维护简单方便!
- 注解不是自己的类使用不了,维护相对复杂
- xml用来管理bean,注解只完成属性的注入。
6.使用JavaConfig实现配置
使用一个JavaConfig类,来替代原来的beans.xml
@Configuration
@ComponentScan("pojo")
//这个类也会被注入到Spring容器中,其本质就是一个@Component
//@Configuration代表这是一个配置类,用于替代beans.xml
public class LewisConfig {
@Bean
//注册一个bean,相当于xml里的一个bean标签
//方法的名字相当于bean标签的id值
//方法的返回类型相当于bean标签的class属性值
public User getUser(){
return new User();
}
}
使用下面的代码来获得Spring容器,同样用getBean方法来获得容器中的对象
ApplicationContext context = new AnnotationConfigApplicationContext(LewisConfig.class);
7.面向切面编程AOP(重点)
横切关注点:横跨多个模块的方法或功能,待加入到业务层实现功能扩充,如日志功能
切面(aspect):横切关注点被模块化的特殊对象,是一个类,即下文中的afterLog类
通知(advice):切面必须完成的工作,即类中的一个方法
目标(target):被通知对象,下文中的UserServiceImpl类的对象
代理(proxy):向目标对象加入通知创建的新对象
切入点(pointcut):切面通知执行的“地点”的定义
连接点(jointpoint):与切入点匹配的执行点
7.1 Spring API接口实现
在保持service层代码不变的基础上,通过AOP新增一些其他的功能。
目录结构树如下
//UserService接口
public interface UserService {
public void add();
public void delete();
public void update();
public void select();
}
//UserServiceImpl实现类
public class UserServiceImpl implements UserService{
public void add() {
System.out.println("增加了一个用户");
}
public void delete() {
System.out.println("删除了一个用户");
}
public void update() {
System.out.println("修改了一个用户");
}
public void select() {
System.out.println("查询了一个用户");
}
}
//afterLog
public class afterLog implements AfterReturningAdvice {
public void afterReturning(Object returnValue, Method method, Object[] objects, Object o1) throws Throwable {
System.out.println("执行了"+method.getName()+"方法,返回的结果为"+returnValue);
}
}
//beforeLog
public class beforeLog implements MethodBeforeAdvice {
public void before(Method method, Object[] objects, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
}
}
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
">
<!-- 注册bean-->
<bean id="userService" class="com.lewis.service.UserServiceImpl"/>
<bean id="afterLog" class="com.lewis.log.afterLog"/>
<bean id="beforeLog" class="com.lewis.log.beforeLog"/>
<aop:config>
<aop:pointcut id="pointcup" expression="execution(* com.lewis.service.UserServiceImpl.*(..))"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcup"/>
<aop:advisor advice-ref="beforeLog" pointcut-ref="pointcup"/>
</aop:config>
</beans>
7.2自定义实现AOP(主要是切面定义)推荐使用
目录树
自定义接口类
<bean id="diy" class="diy.DiyPointCut"/>
<aop:config>
<!--切面:一个类-->
<aop:aspect ref="diy">
<!--切入点-->
<aop:pointcut id="point" expression="execution(* service.UserServiceImpl.*(..))"/>
<!--通知-->
<aop:after method="after" pointcut-ref="point"/>
<aop:before method="before" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
public class DiyPointCut {
public void before(){
System.out.println("===========方法执行前================");
}
public void after(){
System.out.println("===========方法执行后================");
}
}
配置文件
7.3使用注解实现AOP
在类上使用@Aspect,表明这个类是一个切面;在方法上使用@Before,@After等实现通知
<bean id="annotationPointCut" class="service.UserServiceImpl"/>
<!--开启注解支持-->
<aop:aspectj-autoproxy/>
@Aspect
public class AnnotationPointCut {
@Before("execution(* service.UserServiceImpl.*(..))")
public void before(){
System.out.println("===========方法执行前===========");
}
@After("execution(* service.UserServiceImpl.*(..))")
public void after(){
System.out.println("===========方法执行后===========");
}
@Around("execution(* service.UserServiceImpl.*(..))")
public void around(){
System.out.println("===========环绕后===========");
}
}
around的优先级高于before,after