Spring
Spring是一个开放源代码的设计层面框架,他解决的是业务逻辑层和其他各层的松耦合问题,因此它将面向接口的编程思想贯穿整个系统应用.
Spring负责管理项目中的所有对象,可以看作是项目中对象的管家,性质属于容器.与其他框架不冲突,并且还能帮其他框架管理对象.
IOC:Inverse Of Control 反转控制
以前创建对象由开发人员维护,还需要手动注入依赖关系.
Spring反转了创建对象的方式,可以完成对象的创建以及依赖关系注入.
DI:Dependency Injection 依赖注入
实现IOC思想需要DI支持.
注入方式:
set方式注入/构造方法注入/字段注入
注入类型:
值类型注入:八大基本数据类型
引用类型注入:将依赖对象注入
AOP:Aspect Oriented Programming 面向切面编程
横向重复.纵向抽取
动态代理需要手动调用Proxy.newProxyInstance(xx,xx,xx)生成代理对象
//每次容器启动时就会自动创建容器中配置的所有对象
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
User u = (User) ac.getBean("user");
配置文件
web.xml
<!-- 让spring容器随项目(ServletContext)的启动而创建,随项目的关闭而销毁
spring容器被放置在ServletContext即application域中
-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 指定加载spring配置文件的位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
//从ServletContext域中获得spring容器
//1.获得ServletContext对象
ServletContext sc = ServletActionContext.getServletContext();
//2.从sc中获得spring(ApplicationContext)容器
WebApplicationContext ac= WebApplicationContextUtils.getWebApplicationContext(sc);
//3.从容器中获得对象
CustomerService cs = (CustomerService) ac.getBean("customerService");
bean元素
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd ">
<!-- 将User对象交给spring容器管理 -->
<!-- Bean元素:使用该元素描述需要spring容器管理的对象
class属性:被管理对象的完整类名.
name属性:给被管理的对象起个名字.获得对象时根据该名称获得对象.
可以重复.可以使用特殊字符.
id属性: 与name属性一模一样.
名称不可重复.不能使用特殊字符.
结论: 尽量使用name属性.
-->
<!-- scope默认值singleton单例.对象在spring容器中只会存在一个实例
prototype多例
init-method/destroy-method:指定对象在初始化和销毁(spring容器关闭时)时调用的方法
-->
<bean name="user" class="cn.itcast.bean.User" scope="singleton" init-method="init" destroy=method="destroy" ></bean>
<!-- 导入其他spring配置文件 -->
<import resource="cn/itcast/b_create/applicationContext.xml"/>
</beans>
属性注入:set方法注入/构造方法注入/p名称空间注入/spel注入
set方法注入:
<bean name="user" class="cn.it.bean.User">
<property name="name" value="tom"></property>
<property name="age" value="18"></property>
<property name="car" ref="car"></property>
</bean>
<bean name="car" class="cn.it.bean.Car">
<property name="name" value="audi"></property>
<property name="color" value="black"></property>
</bean>
构造方法注入:
<!-- index/type可选 -->
<bean name="user" class="cn.it.bean.User">
<constructor-arg name="name" value="tom" index="0" type="java.lang.String"></constructor-arg>
<constructor-arg name="age" value="18" index="1"></constructor-arg>
<constructor-arg name="car" ref="car" index="2"></constructor-arg>
</bean>
<bean name="car" class="cn.it.bean.Car">
<property name="name" value="audi"></property>
<property name="color" value="black"></property>
</bean>
复杂类型注入:
<bean name="cb" class="cn.it.CollectionBean">
<!-- 如果数组中只准备注入一个值(对象),直接使用value|ref即可
<property name="arr" value="tom" ></property>
-->
<!-- array注入,多个元素注入 -->
<property name="arr">
<array>
<value>tom</value>
<value>jerry</value>
<ref bean="user4" />
</array>
</property>
<!-- 如果List中只准备注入一个值(对象),直接使用value|ref即可
<property name="list" value="jack" ></property>-->
<property name="list" >
<list>
<value>jack</value>
<value>rose</value>
<ref bean="user3" />
</list>
</property>
<!-- map类型注入 -->
<property name="map" >
<map>
<entry key="url" value="jdbc:mysql:///crm" ></entry>
<entry key="user" value-ref="user4" ></entry>
<entry key-ref="user3" value-ref="user2" ></entry>
</map>
</property>
<!-- prperties 类型注入 -->
<property name="prop" >
<props>
<prop key="driverClass">com.jdbc.mysql.Driver</prop>
<prop key="userName">root</prop>
<prop key="password">1234</prop>
</props>
</property>
</bean>
使用注解配置spring
<!-- 指定扫描cn.itcast.bean包下的所有类中的注解.
注意:扫描包时.会扫描指定包下的所有子孙包
-->
<context:component-scan base-package="cn.itcast.bean"></context:component-scan>
在类中使用注解完成配置
注册对象到Spring容器:
@Component
@Controller
@Service
@Repository
指定对象的作用范围:
@Scope(scopeName=“singleton/prototype”)
属性注入:
值类型注入:@Value
引用类型注入:@Autowired:自动装配(在容器中找到类型匹配的对象并赋值)
? ? ? ? @Qualifier(“car”):配合@Autowired,通过在容器中的名字来指定装配的对象 ? ?
@Resource(name=“car”):手动注入,指定注入哪个名称的对象
@Component("user")
@Scope(scopeName="prototype")
public class User {
//通过反射的Field赋值(破坏了对象的封装性)
@Value("tom")
private String name;
@Value("18")
private Integer age;
@Autowired
private Car car;
//通过set方法赋值
@Value("tom")
public void setName(String name) {
this.name = name;
}
get/set...
}
spring整合junit测试
//帮我们创建容器
@RunWith(SpringJUnit4ClassRunner.class)
//指定创建容器时使用哪个配置文件
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo {
//将名为user的对象注入到u变量中
@Resource(name="user")
private User u;
@Test
public void fun1() {
System.out.println(u);
}
@Test
public void fun2() {
System.out.println(u);
}
@Test
public void fun3() {
System.out.println(u);
}
}
Spring AOP
Spring能够为容器中管理的对象生成动态代理对象,只需在配置文件中进行配置即可.
Spring实现aop的原理:动态代理/cglib代理
动态代理:被代理对象必须要实现接口,才能生成代理对象.(spring优先使用此方法)
cglib代理:第三方代理技术.可以对任何类生成代理.原理是对目标对象进行继承代理.
?
Spring的aop名词解释
Join point(连接点):目标对象中,所有可以增强的方法
Point cut(切入点):目标对象中,已经增强的方法
Advice(通知/增强):增强的代码
Target(目标对象):被代理对象
Weaving(织入):将通知应用到连接点
Proxy(代理):将通知织入到目标对象之后,形成代理对象
Aspect(切面):切入点+通知
?
通知类
//通知类
public class MyAdvice {
//前置通知
// |-目标方法运行之前调用
//后置通知(如果出现异常不会调用)
// |-在目标方法运行之后调用
//环绕通知
// |-在目标方法之前和之后都调用
//异常拦截通知
// |-如果出现异常,就会调用
//后置通知(无论是否出现 异常都会调用)
// |-在目标方法运行之后调用
//----------------------------------------------------------------
//前置通知
public void before(){
System.out.println("这是前置通知!!");
}
//后置通知
public void afterReturning(){
System.out.println("这是后置通知(如果出现异常不会调用)!!");
}
//环绕通知
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("这是环绕通知之前的部分!!");
Object proceed = pjp.proceed();//调用目标方法
System.out.println("这是环绕通知之后的部分!!");
return proceed;
}
//异常通知
public void afterException(){
System.out.println("出事啦!出现异常了!!");
}
//后置通知
public void after(){
System.out.println("这是后置通知(出现异常也会调用)!!");
}
}
?
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd ">
<!-- 准备工作: 导入aop(约束)命名空间 -->
<!-- 1.配置目标对象 -->
<bean name="userService" class="cn.itcast.service.UserServiceImpl" ></bean>
<!-- 2.配置通知对象 -->
<bean name="myAdvice" class="cn.itcast.d_springaop.MyAdvice" ></bean>
<!-- 3.配置将通知织入目标对象 -->
<aop:config>
<!-- 配置切入点
public void cn.itcast.service.UserServiceImpl.save()
void cn.itcast.service.UserServiceImpl.save()
* cn.itcast.service.UserServiceImpl.save()
* cn.itcast.service.UserServiceImpl.*()
* cn.itcast.service.*ServiceImpl.*(..)
* cn.itcast.service..*ServiceImpl.*(..)
-->
<aop:pointcut expression="execution(* cn.itcast.service.*ServiceImpl.*(..))" id="pc"/>
<aop:aspect ref="myAdvice" >
<!-- 指定名为before方法作为前置通知 -->
<aop:before method="before" pointcut-ref="pc" />
<!-- 后置 -->
<aop:after-returning method="afterReturning" pointcut-ref="pc" />
<!-- 环绕通知 -->
<aop:around method="around" pointcut-ref="pc" />
<!-- 异常拦截通知 -->
<aop:after-throwing method="afterException" pointcut-ref="pc"/>
<!-- 后置 -->
<aop:after method="after" pointcut-ref="pc"/>
</aop:aspect>
</aop:config>
</beans>
?
使用注解完成织入配置
<!-- 开启使用注解完成织入 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
@Aspect:表示该类是通知类
指定通知类中的方法:
@Before(“execution(* cn.itcast.service.ServiceImpl.(…))”):前置通知
@AfterReturning("…"):后置通知,出现异常不会调用
@Around("…"):环绕通知
@AfterThrowing("…"):异常通知
@After("…"):后置通知
?
JDBCTemplate
Spring中提供了一个可以操作数据库的jdbc模板对象,封装了jdbc技术.
JDBCTemplate与DBUtils中的QueryRunner非常相似.
//准备连接池(需要准备好配置文件)
ComboPooledDateSource dataSource = new ComboPooledDateSource();
//根据连接池创建JDBC模板对象
JdbcTemplate jt = new JdbcTemplate(dataSource);
//书写sql并执行
String sql = "insert into t_user values(null,'rose')";
jt.update(sql);
Spring整合jdbc
<!-- 1.将连接池放入spring容器 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///abc"></property>
<property name="user" value="root"></property>
<property name="password" value="1234"></property>
</bean>
<!-- 2.将JDBCTemplate放入spring容器 -->
<bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 3.将UserDao放入spring容器 -->
<bean name="userDao" class="cn.itcast.dao.UserDaoImpl">
<property name="jt" ref="jdbcTemplate"></property>
</bean>
JdbcDaoSupport
//继承JdbcDaoSupport,spring会根据连接池创建JdbcTemplate
//通过父类方法getJdbcTemplate()获取JdbcTemplate,无需手动准备JdbcTemplate
//需要更改配置文件,删掉jdbcTemplate部分,并将dataSource注入到userDao中
public class UserDaoImpl extends JdbcDaoSupport implements UserDao {
//private JdbcTemplate jt;
public void save(User u) {
String sql = "insert into t_user values(null,?)";
super.getJdbcTemplate.update(sql, u.getName());
}
}
?
spring读取properties配置
<!-- 指定spring读取db.properties配置 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 1.将连接池放入spring容器 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 2.将JDBCTemplate放入spring容器 -->
<bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 3.将UserDao放入spring容器 -->
<bean name="userDao" class="cn.itcast.dao.UserDaoImpl">
<property name="jt" ref="jdbcTemplate"></property>
</bean>
?
Spring事务管理
? Spring封装了事务管理代码(打开/提交/回滚事务)
因为在不同平台(jdbc/hibernate/mybatis),操作事务的代码各不相同,spring提供了一个接口:PlatformTransactionManager(平台事务管理器).它声明了事务操作的方法,针对不同平台提供相应的实现类.
DataSourceTransactionManager
HibernateTransactionManager
spring中事务管理的核心对象就是TransactionManager对象
spring管理事务的属性介绍
事务的隔离级别
是否只读
事务的传播行为:决定业务方法之间互相调用时,事务该如何处理
spring提供了7种解决方式,使用默认PROPAGATION_REQUIRED即可:支持当前事务,如果不存在,就新建一个.
Spring管理事务方式
1.编码式
2.xml配置(aop)
applicationContext.xml
<!-- 事务核心管理器,封装了所有事务操作.依赖于连接池 -->
<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource">
</bean>
<!-- 配置事务通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 以方法为单位,指定方法应用什么事务属性
isolation:隔离级别
propagation:传播行为
read-only:是否只读
-->
<tx:method name="save*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
<tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
<tx:method name="delete*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
<tx:method name="get*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />
</tx:attributes>
</tx:advice>
<!-- 配置织入 -->
<aop:config>
<!-- 配置切入点表达式 -->
<aop:pointcut expression="execution(* cn.itcast.service.*ServiceImpl.*(..))" id="txPc" />
<!-- 配置切面: 通知+切入点 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPc" />
</aop:config>
3.注解配置(aop)
applicationContext.xml
<!-- 事务核心管理器,封装了所有事务操作.依赖于连接池 -->
<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource">
</bean>
<!-- 开启使用注解管理aop事务 -->
<tx:annotation-driven/>
?
//注解也可以加在方法上
@Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=true)
public class AccountServiceImpl implements AccountService {
private AccountDao ad;
@Override
@Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=false)
public void transfer(xx,xx,xx) {
...
}
}