一、Spring
使用spring需要导入spring-webmvc这个jar包这个jar整合了spring所有spring所需的包分别为:
Spring AOP:Spring的面向切面编程,提供AOP(面向切面编程)的实现
Spring Aspects:Spring提供的对AspectJ框架的整合
Spring Beans:Spring IOC的基础实现,包含访问配置文件、创建和管理bean等,所有应用都用到。
Spring Context:在基础IOC功能上提供扩展服务,此外还提供许多企业级服务的支持,有邮件服务、任务调度、JNDI定位,EJB集成、远程访问、缓存以及多种视图层框架的支持。
Spring Context Support:Spring context的扩展支持,用于MVC方面。
Spring Core:Spring的核心工具包 ,其他包依赖此包
Spring expression:Spring表达式语言
Spring JDBC:对JDBC 的简单封装
Spring test:对JUNIT等测试框架的简单封装
Spring tx:为JDBC、Hibernate、JDO、JPA等提供的一致的声明式和编程式事务管理。
Spring web:包含Web应用开发时,用到Spring框架时所需的核心类,包括自动载入WebApplicationContext特性的类、Struts与JSF集成类、文件上传的支持类、Filter类和大量工具辅助类。
1、xml配置
1.1、bean标签
bean的使用方法&常用属性:
<bean id="..." name="var1,var2 var3;var4" class="..." scope="..."></bean>
id:bean 的唯一标识符,相当于别名
name:相当于别名(可以取多个别名在name中以逗号、空格、分号分隔多个别名)
class:bean 对象所对应的全限定名:包名+类型
scope:
属性值:
singleton:单例模式(所有人共享这个对象)
prototype:多例模式(每个人使用都会创建都是不同的对象)
注意点:scope默认使用单例模式
当配置文件被加载的时候,所有的bean(对象)都会被实例化
公用的属性:
ref:引用spring容器中创建好的对象(bean)
value:具体的值,基本数据类型!
name:类中的属性名
property用法:
property:setter注入属性
第一种property标签的使用方式:
<property name="...""/>
<value>基本类型值</value>
<ref>引用类型值</ref>
...
</property>
第二种property标签的使用方式:
<property name="..."" value="基本类型值" ref="引用类型值"/></property>
如果只是基本类型或引用类型的话两种方式都可以使用(本人推荐使用第二种)
如果是list、map、set、array、null、bean、props等等这些类型那么就只能使第一种方式
constructor-arg用法:
<constructor-arg index="..." name="..." type="..." value="..."/>
constructor-arg:构造器注入,不使用默认走无参构造
第一种注入方式index:构造器的第一个值为0以此类推
第二种注入方式name:通过构造器的参数名名
第三种注入方式type:通过构造器需要注入的数据类型进行注入(引用类型需要写类的全路径),如果有两个相同类型那么他会先给第一个相同参数类型的参数注入值
1.2、alias标签
alias用法:
<alias name="..." alias="..."/>
alias:给spring容器中创建好的对象起别名
name:spring容器中创建好的对象(bean)
1.3、import标签
import用法:
<import resource="*.xml"/>
resource:将多个xml配置文件合并到当前配置文件中(适合团队开发)
2、自动装配&组件使用
我们使用注解&组件之前需要导入spring-context这个包,如果我们在maven中导入了spring-webmvc这个包那么就不需要再导入了
使用注解实现自动装配和组件使用的话那么需要在xml中beans标签中的xmlns属性中加入
xmlns:context="http://www.springframework.org/schema/context"
和在xsi:schemaLocation属性中加入
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
自动装配的用法:
autowire:
自动给指定的类中的属性注入值(它会在xml配置文件中寻找同类型的bean然后注入值)
属性值:
ByType:根据在xml配置文件中找class类型相同的bean进行注入
ByName:根据在xml配置文件中找id/name相同的bean进行注入
第一种通过bean实现:
<bean name="..."" class="..." autowire=""/></bean>
第二种通过注解实现:
开启注解扫描只有开启或者使用组件扫描如果不开启那么就不能识别到注解:
<context:annotation-config/>
使用:
在被bean管理的类中的属性上面加上注解@AutoWire这个注解这个属性必须是引用类型
如果需要给基本类型自动装配的话那么使用@Value(通过@value(value = "")可以设置默认值)这个注解实现自动注入
组件的用法:
使用组件需要开启注解扫描:
<!--组件扫描器,开启之后会自动开启注解扫描器-->
<context:component-scan base-package="..."/>
base-package:需要指定扫描那个包下的组件(包全路径)
组件分为:
实体类组件:@Component(一般都使用在实体类中所以个人称它为实体类组件)
数据层组件:@Repository
业务层组件:@Service
视图层组件:@Controller
注意点:数据层、业务层、视图层是组件的原因是它们使用了@Component
使用了组件的类就可以不需要在xml配置文件中去创建对应的bean,会自动给使用组件的类在xml配置文件中创建对应的bean
(当然你还是可以去xml配置文件中创建bean毕竟xml配置文件中更加灵活)
3、组件+JavaClass实现配置
使用JavaClass实现配置需要使用组件
在JavaClass上面需要加上@ComponentScan("扫描包路径")组件扫描与@Configuration配置的两个注释
@Configuration
@ComponentScan("...")
public class JavaConfig {
}
在类中的方法上加上@Bean这个注解就表示这个方法是个bean了方法返回类型就是你想拿到的类,return new 你想要的对象;
@Bean
public User getUser() {
return new User();
}
获取用获取bean方式
public void test(){
ApplicationContext ac = new AnnotationConfigApplicationContext(JavaConfig.class);
User user = ac.getBean("user", User.class);
}
并不推荐通过JavaClass实现配置,了解即可
4、AOP实现
使用AOP需要使用Spring-AOP或aspectjweaver(功能比spring-aop包功能强大)织入包
使用AOP的话那么需要在xml中beans标签中的xmlns属性中加入
xmlns:aop="http://www.springframework.org/schema/aop"
和在xsi:schemaLocation属性中加入
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/context/spring-aop.xsd
第一种实现方式(使用原生Spring API接口):
第一步:
我们需要写一个类并且实现AfterReturningAdvice, MethodBeforeAdvice接口并且实现里面的方法
afterReturning:方法执行后调用的方法
before:方法执行前会调用的方法
public class AfterLog implements AfterReturningAdvice, MethodBeforeAdvice {
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
}
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
}
}
然后将这个类写如bean中或者使用组件@Component
<bean id="afterLog" class="com.xiao.log.AfterLog"/>
第二步:
在配置文件中写插入点了:
配置aop:需要导入aop的约束
<aop:config>
切入点:expression:表达式,expression(要执行的位置全路径+类名* * * * *)
<aop:pointcut id="pointcut" expression="execution(* 包路径+类名.方法(参数))"/>
执行环绕增强!
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
advice-ref:引用配置文件中的afterLog,他会将这个类中实现的两个方法环绕插入到pointcut中的方法
pointcut-ref:引用上面的切入点pointcut
</aop:config>
第二种实现方式(自定义类进行实现,使用的是spring-aop包进行实现):
第一步:
编写一个类写入你想插入的方法
public class DiyPointCut {
public void before() {
}
public void after() {
}
}
然后将这个类写如bean中或者使用组件@Component
<bean id="diyPointCut" class="com.xiao.diy.diyPointCut"/>
第二步:
在配置文件中自定义切面:
<aop:config>
自定义切面,ref 要引用的类
<aop:aspect ref="diyPointCut">
切入点:expression:表达式,expression(要执行的位置全路径+类名* * * * *)会找到方法然后给到id
<aop:pointcut id="point" expression="execution(* 包路径+类名.方法(参数))"/>
在切入到point方法执行之前
<aop:before method="before" pointcut-ref="point"/>
在切入到point方法执行之后
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
上面两种方式使用的是spring-aop包进行实现,下面的是使用了aspectjweaver织入包进行实现aop的织入
第三种实现方式(自定义类并使用注解进行实现):
第一步:
编写一个类并且在类上使用@Aspect(切面)这个注解
@Aspect
public class AnnotationPointCut {
@Before:表示被切入的方法执行之前先执行这个方法
execution:表示你要将方法切入那个类下的哪一个方法execution(包全路径+类名+方法名+(方法参数),可以使用(*)通配符)
@Before("execution(* com.xiao.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("方法执行之前");
}
@After:表示被切入的方法先执行之后再来执行这个方法
execution:表示你要将方法切入那个类下的哪一个方法execution(包全路径+类名+方法名+(方法参数),可以使用(*)通配符)
@After("execution(* com.xiao.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("方法执行之后");
}
@Around:表示被切入的方法进行环绕执行,pj.proceed()表示执行需要被切入的方法你可以在方法前后增加业务
execution:表示你要将方法切入那个类下的哪一个方法execution(包全路径+类名+方法名+(方法参数),可以使用(*)通配符)
@Around("execution(* com.xiao.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint pj) throws Throwable {
System.out.println("方法执行前");
pj.proceed();
System.out.println("方法执行后");
}
}
5、Spring整合Mybatis
整合mybatis之前需要导入spring-webmvc、mybatis、mybatis-spring、spring-jdbc、mysql-connector-java、junit、spring-test这些包
配置文件:
1.编写DataSource数据源,这里使用的是jdbc的数据源修改数据源在class中修改
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///worktest?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="xcq2064557753"/>
</bean>
参数:
driverClassName:mysql驱动
url:数据库路径
username:数据库用户名
password:数据库密码
2.创建sqlSessionFactory这个对象
<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--绑定mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/xiao/dao/*.xml"/>
</bean>
参数:
dataSource:数据源
configLocation:绑定mybatis配置文件 value:classpath: + 配置文件名 + .xml(mybatis配置文件路径,默认扫描本项目下的resources文件夹下)
mapperLocations:绑定mapper value:classpath: + 包全路径 + mapper文件名 + .xml
3.创建sqlSession对象
sqlSessionTemplate:就是我们使用的sqlSession
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--只能使用构造器注入sqlSessionFactory,因为它没有set方法-->
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
第一种实现方式(创建mapper实现类使用SqlSessionTemplate进行实现):
1.实现类
@Repository
public class UserMapperImpl implements UserMapper {
可以使用@AutoWire自动将配置文件中的SqlSession注入进来也可以在配置文件中创建userMapperImpl这个类的bean进行setter注入
private SqlSessionTemplate sqlSession;
要注入必须得有setter方法
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSession = sqlSessionTemplate;
}
@Override
public List<User> queryUser() {
获取mapper.xml文件
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
执行mapper.xml文件中的id为queryUser的方法返回结果
List<User> users = mapper.queryUser();
将结果返回给业务层
return users;
}
}
2.在bean绑定实现类,使用属性注入sqlSession,也可以使用@AutoWire自动装配
<bean id="userMapperImpl" class="com.xiao.dao.UserMapperImpl" >
<property name="sqlSession" ref="sqlSession"/>
</bean>
3.测试类
@Test
public void test(){
获取spring配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext-mybatis.xml");
在配置文件中获取userMapperImpl这个bean
UserMapper userMapper = ac.getBean("userMapperImpl", UserMapper.class);
调用userMapperImpl中的查询方法
List<User> users = userMapper.queryUser();
for (User user : users) {
System.out.println(user);
}
}
第二种实现方式(mapper实现类继承SqlSessionDaoSupport这个类进行实现):
1.实现类
@Repository
public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper {
@Override
public List<User> queryUser() {
return getSqlSession().getMapper(UserMapper.class).queryUser();
}
}
我们继承了SqlSessionDaoSupport这个类之后我们就可以使用getSqlSession这个方法了不过需要在配置文件中设置如下
<bean id="userMapperImpl" class="com.xiao.dao.UserMapperImpl" >
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
sqlSessionFactory这个属性是SqlSessionDaoSupport的由于我们继承了它所以有了它的所有方法
我们这里设置的属性是sqlSessionFactory它需要的的参数是sqlSessionFactory而不是第一种需要sqlSession所以这里我们这里直接给它sqlSessionFactory这个对象
2.测试类和第一种方法一样的测试类
这里推荐使用第二种方式进行实现
6、结合AOP实现事务织入
第一步:
在配置文件中配置声明式事务
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
我们这里使用的是spring-jdbc的事务管理
第二步:
配置事务通知
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--配置事务的传播特性:new propagation = -->
<!--给哪些方法配置事务 一般将事务设置在add* delete* update* query*-->
<tx:method name="*" propagation="REQUIRED"/> *:表示所有方法都添加事务
<tx:method name="add*" propagation="REQUIRED"/> add*:表示以add开头的方式都添加事务
<tx:method name="delete*" propagation="REQUIRED"/> delete*:表示以delete开头的方式都添加事务
<tx:method name="update*" propagation="REQUIRED"/> update*:表示以update开头的方式都添加事务
<tx:method name="query*" propagation="REQUIRED"/> query*:表示以query开头的方式都添加事务
</tx:attributes>
</tx:advice>
通过aop配置事务
<aop:config>
配置需要被插入的方法,expression:正则表达式
<pointcut id="txPointcut" expression="expression("* 包全路径+类名+方法名+方法参数")"/>
配置需要插入的事务
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>