Spring : 春天 --->给软件行业带来了春天
2002年,Rod Jahnson首次推出了Spring框架雏形interface21框架。
2004年3月24日,Spring框架以interface21框架为基础,经过重新设计,发布了1.0正式版。
很难想象Rod Johnson的学历 , 他是悉尼大学的博士,然而他的专业不是计算机,而是音乐学。
Spring理念 : 使现有技术更加实用 . 本身就是一个大杂烩 , 整合现有的框架技术
官网 : http://spring.io/
官方下载地址 : https://repo.spring.io/libs-release-local/org/springframework/spring/
GitHub : https://github.com/spring-projects
1、Spring是一个开源免费的框架 , 容器 .
2、Spring是一个轻量级的框架 , 非侵入式的 .
3、控制反转 IoC , 面向切面 Aop
4、对事物的支持 , 对框架的支持
.......
一句话概括:
Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器(框架)。
Spring 框架是一个分层架构,由 7 个定义良好的模块组成。Spring 模块构建在核心容器之上,核心容器定义了创建、配置和管理 bean 的方式 .
组成 Spring 框架的每个模块(或组件)都可以单独存在,或者与其他一个或多个模块联合实现。每个模块的功能如下:
Spring Boot与Spring Cloud
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.9</version>
</dependency>
</dependencies>
控制反转IoC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IOC的一种方法,在没有IoC的程序中,我们使用面向对象的编程,对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。
采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。
控制反转是通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是IoC容器,其实现方法是依赖注入(Dependency Injection,DI)。
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="hello" class="com.dzj.pojo.Hello">
<property name="name" value="dengzhijiang"></property>
</bean>
<!-- more bean definitions go here -->
</beans>
读取容器
ApplicationContext context = new ClassPathXmlApplicationContext("benas.xml");
<bean id="userService" class="com.dzj.service.impl.UserServiceImpl">
<!--
ref:引用Spring容器中已经创建好的对象
value:基本的值,基本数据类型
-->
<property name="userDao" ref="oracle"></property>
</bean>
private String name;
private Address address;
private String[] books;
private List<String> hobbies;
private Map<String,String> card;
private Set<String> games;
private String wife;
<bean id="address" class="com.dzj.pojo.Address">
<property name="address" value="湛江市"></property>
</bean>
<bean id="student" class="com.dzj.pojo.Student">
<!--第一种,普通值注入,value-->
<property name="name" value="邓志江" />
<!--第二种,bean注入,ref-->
<property name="address" ref="address"/>
<!--数组-->
<property name="books">
<array>
<value>红楼梦</value>
<value>西游记</value>
<value>水浒传</value>
<value>三国演义</value>
</array>
</property>
<!--List-->
<property name="hobbies">
<list>
<value>听歌</value>
<value>写字</value>
<value>运动</value>
</list>
</property>
<!--map-->
<property name="card">
<map>
<entry key="省份证" value="44088219981211"></entry>
<entry key="银行卡" value="201824113212"></entry>
</map>
</property>
<!--set-->
<property name="games">
<set>
<value>LOL</value>
<value>COC</value>
<value>BOB</value>
</set>
</property>
<!--null-->
<property name="wife">
<null/>
</property>
<!--properties-->
<property name="info">
<props>
<prop key="driver">20182411</prop>
<prop key="gender">男</prop>
<prop key="username">小明</prop>
<prop key="password">123456</prop>
</props>
</property>
</bean>
c命名空间和p命名空间的注入:不能直接使用,需要导入xml约束
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
<!--p命名空间注入,可以直接注入属性的值,property-->
<bean id="user" class="com.dzj.pojo.User" p:name="邓志江" p:age="22"></bean>
<!--c命名空间注入,通过构造器注入,construct-args-->
<bean id="user2" class="com.dzj.pojo.User" c:name="林勇" c:age="22" ></bean>
1、单例模式(Spring默认模式)
<bean id="user" class="com.dzj.pojo.User" p:name="邓志江" p:age="22" scope="singleton"></bean>
2、原型模式(每次从容器中get的时候,都会产生一个新的对象!
<bean id="user2" class="com.dzj.pojo.User" c:name="林勇" c:age="22" scope="prototype"></bean>
3、其余的 @request、@sesstion、@application 这些只能在web开发中使用到!
private String name;
@Autowired
private Cat cat;
@Autowired
private Dog dog;
<!--自动装配需要加上-->
<context:annotation-config/>
<bean id="cat" class="com.dzj.pojo.Cat"></bean>
<bean id="dog" class="com.dzj.pojo.Dog"></bean>
<!--
byName: 会自动在容器的上下文中查找,和自己对象set方法后面值对应的 beanid!
byType: 会自动在容器的上下文中查找,和自己对象属性类型相同的 bean!
-->
<bean id="person" class="com.dzj.pojo.Person" autowire="byName">
<property name="name" value="小公羊"/>
<!--<property name="cat" ref="cat"/>-->
<!--<property name="dog" ref="dog"/>-->
</bean>
注解说明
-@autowired:自动装配通过类型、名字
? 如果@autowired没有自动装配上属性,则需要通过@qualifier(value = “ ”)
-@nullable 如果字段标记了这个注解,说明这个字段可以为null
-@resource:自动装配通过类型、名字
将类注册到容器中
-@component :组件,放在这个类上,说明这个类被Spring管理了,就是bean!
? 等价于:
-@Value: 给属性赋值,等价于:
<!--需要在 xml 中开启注解扫描,才能检测到注册bean的类-->
<context:component-scan base-package="com.dzj.dao"/>
@component组件的衍生:在web开发中,会按照三层架构分层
dao【@Repository】
service【@Service】
controller【@Controller】
这四个注解功能都是一样的,都是将我们的类注册到Spring容器
第一种方法:
1、在实体类的头部添加注解--@component
@Value注解用来给对象的属性赋值
@Component
public class User {
@Value("zhijiang")
public String name;
public void show(){
System.out.println("成功了...");
}
}
2、在配置类 MyConfig 中添加两个注解
--@configuration ---> 代替 beans.xml 文件,相当于这个类就是一个spring容器
--@componentScan --> 用来扫描实体类,哪些类注册了 bean
@Configuration
@ComponentScan("com.dzj.pojo")
public class MyConfig {
}
3、获取容器中的对象
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
User user = context.getBean("user", User.class);
第二种方法:
1、无需在实体类中添加多余的注解,若想给对象的属性赋值,只需用@Value注解给属性赋值即可
public class User {
@Value("zhijiang")
public String name;
public void show(){
System.out.println("成功了...");
}
}
2、只需在配置类中添加一个返回对象的方法,并且在该方法上方添加一个注解@bean
public class MyConfig {
@Bean
public User getUser(){
return new User();
}
}
@bean就是beans.xml文档中的
方法名:getUser就是
new user():就是就是
3、获取容器中的对象
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
User user = context.getBean("getUser", User.class);
public interface UserService {
public void add();
public void delete();
public void update();
public void query();
}
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 query() {
System.out.println("查询了一个用户");
}
}
//等会我们用这个类,自动生成代理类
public class ProxyInvocationHandler implements InvocationHandler {
//被代理的接口
private Object target;
public void setTarget(Object target) {
this.target = target;
}
//生成得到代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
}
//处理代理实例,并返回结果
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
PrintLog(method.getName());
Object result = method.invoke(target,args);
fee();
return result;
}
public void PrintLog(String msg){
System.out.println("[debug]执行了"+msg+"方法!");
}
public void fee(){
System.out.println("收中介费");
}
}
public static void main(String[] args) {
//真实角色
UserServiceImpl userService = new UserServiceImpl();
//代理角色,不存在,从ProxyInvocationHandler类中动态生成
ProxyInvocationHandler pih = new ProxyInvocationHandler();
//在 ProxyInvocationHandler 类中通过setTarget()方法得到要被代理的真是角色 userService
pih.setTarget(userService);
// 获取代理角色
UserService proxy = (UserService) pih.getProxy();
proxy.add(); //执行代理实例,以及一些附属的操作
}
使用原生态 API接口**(主要是SpringAPI接口实现)
public interface UserService {
public void add();
public void delete();
public void update();
public void query();
}
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 query() {
System.out.println("查询了一个用户!");
}
}
public class Log implements MethodBeforeAdvice {
//method:要执行的目标对象的方法
//args:参数
//target:目标对象
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
}
}
public class AfterLog implements AfterReturningAdvice {
//returnValue:返回值
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("执行了"+method.getName()+"方法,返回结果为:"+returnValue);
}
}
<?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 https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--注册bean-->
<bean id="userService" class="com.dzj.service.UserServiceImpl"/>
<bean id="log" class="com.dzj.log.Log"/>
<bean id="afterLog" class="com.dzj.log.AfterLog"/>
<!--方式一:使用原生态 API接口-->
<!--配置aop:需要导入aop的约束-->
<aop:config>
<!--创建切入点:expression:表达式,excution(要执行的位置!* * * * *)-->
<aop:pointcut id="pointcut" expression="execution(* com.dzj.service.UserServiceImpl.*(..))" /> <!--执行环绕增强,把增强引入切入点-->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
</beans>
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//动态代理的是接口,而不是接口的实现类
UserService userService = context.getBean("userService", UserService.class);
userService.query();
}
}
public interface UserService {
public void add();
public void delete();
public void update();
public void query();
}
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 query() {
System.out.println("查询了一个用户!");
}
}
public class diy {
public void before(){
System.out.println("*****方法执行前*****");
}
public void after(){
System.out.println("*****方法执行后*****");
}
}
<!--注册bean-->
<bean id="userService" class="com.dzj.service.UserServiceImpl"/>
<bean id="log" class="com.dzj.log.Log"/>
<bean id="afterLog" class="com.dzj.log.AfterLog"/>
<!--方式二:自定义类-->
<bean id="diy" class="com.dzj.customize.diy"/>
<aop:config>
<!--自定义切面,ref 要引用的类-->
<aop:aspect ref="diy">
<!--切入点-->
<aop:pointcut id="point" expression="execution(* com.dzj.service.UserServiceImpl.*(..))"/>
<!--通知-->
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//动态代理的是接口,而不是接口的实现类
UserService userService = context.getBean("userService", UserService.class);
userService.query();
}
}
@Aspect //标注这个类是一个切面
public class AnnotationPointCut {
@Before("execution(* com.dzj.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("*****方法执行前*****");
}
@After("execution(* com.dzj.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("*****方法执行后*****");
}
//在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点
@Around("execution(* com.dzj.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint jp) throws Throwable {
System.out.println("环绕前");
Signature signature = jp.getSignature();//获得签名
System.out.println("signature:"+signature);
Object proceed = jp.proceed();//执行方法
System.out.println("环绕后");
}
}
<!--方式三-->
<!--创建切入点-->
<bean id="annotationPointCut" class="com.dzj.customize.AnnotationPointCut"/>
<!--开启注解支持--><aop:aspectj-autoproxy/>
提供声明式事务,允许用户自定义切面
(1)横切切入点:跨越应用程序多个模块的功能和方法。即是,与我们逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志、安全、缓存、事务等等......
(2)切面(ASPECT):横切关注点 被模块化的特殊对象。即,它是一个类。
(3)通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。
(4)目标(Tatget):被通知的对象。
(5)代理(Proxy):向目标对象应用通知之后创建的对象。
(6)切入点(PointCut):切面通知 执行的 “地点” 的定义。
(7)连接点(JoinPoint):与切入点匹配的执行点。
@Data
public class User {
private int uid;
private String username;
private String password;
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="com.dzj.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</dataSource>
</environment>
</environments>
<!-- 将mapper文件加入到配置文件中,注册接口 -->
<mappers>
<mapper class="com.dzj.mapper.UserMapper"></mapper>
</mappers>
</configuration>
public interface UserMapper {
public List<User> selectUser();
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dzj.mapper.UserMapper">
<select id="selectUser" resultType="user">
select * from test.user;
</select>
</mapper>
public class MyTest {
@Test
public void test() throws IOException {
String resources = "mybatis-config.xml";
InputStream in = Resources.getResourceAsStream(resources);
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(in);
SqlSession sqlSession = sessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userlist = mapper.selectUser();
for(User user:userlist){
System.out.println(user);
}
}
}
<!--DataSource使用Spring的数据源替换Mybatis的配置 c3p0、dbcp、druid也可以
我们这里使用Spring提供的JDBC : org.springframework.jdbc.datasource
-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</bean>
<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--绑定Mybati配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/dzj/mapper/*.xml"/>
</bean>
<!--SqlSessionTemplate:就是我们使用的sqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--只能使用构造器注入SQLSessionFactory,因为它没有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
public class UserMapperImpl implements UserMapper {
//我们所有的操作,都是用sqlSession来执行,在原来,现在都使用SqlSessionTemplate
private SqlSessionTemplate sqlSession;
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
public List<User> selectUser() {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.selectUser();
}
}
<import resource="spring-dao.xml"/>
<bean id="userMapper" class="com.dzj.mapper.UserMapperImpl">
<property name="sqlSession" ref="sqlSession"/>
</bean>
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
for(User user:userMapper.selectUser()){
System.out.println(user);
}
事务ACID原则:
<!--配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--结合AOP实现事务的织入-->
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--给哪些事务配置方法-->
<!--配置事务的传播特性:new propagation-->
<tx:attributes>
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<tx:method name="query" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
<!--"name*" 代表所有方法-->
</tx:attributes>
</tx:advice>
<!--配置事务的切入-->
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.dzj.mapper.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
Spring在不同的事务管理API之上定义了一个抽象层,使得开发人员不必了解底层的事务管理API就可以使用Spring的事务管理机制。Spring支持编程式事务管理和声明式的事务管理。
编程式事务管理
声明式事务管理
使用Spring管理事务,注意头文件的约束导入 : tx
xmlns:tx="http://www.springframework.org/schema/tx"
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
事务管理器
JDBC事务
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
配置好事务管理器后我们需要去配置事务的通知
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--配置哪些方法使用什么样的事务,配置事务的传播特性-->
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<tx:method name="search*" propagation="REQUIRED"/>
<tx:method name="get" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
spring事务传播特性:
事务传播行为就是多个事务方法相互调用时,事务如何在这些方法间传播。spring支持7种事务传播行为:
Spring 默认的事务传播行为是 PROPAGATION_REQUIRED,它适合于绝大多数的情况。
假设 ServiveX#methodX() 都工作在事务环境下(即都被 Spring 事务增强了),假设程序中存在如下的调用链:Service1#method1()->Service2#method2()->Service3#method3(),那么这 3 个服务类的 3 个方法通过 Spring 的事务传播机制都工作在同一个事务中。
就好比,我们刚才的几个方法存在调用,所以会被放在一组事务当中!
配置AOP
导入aop的头文件!
<!--配置aop织入事务-->
<aop:config>
<aop:pointcut id="txPointcut" expression="execution(* com.kuang.dao.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
进行测试
删掉刚才插入的数据,再次测试!
@Test
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserMapper mapper = (UserMapper) context.getBean("userDao");
List<User> user = mapper.selectUser();
System.out.println(user);
}
思考问题?
为什么需要配置事务?
原文:https://www.cnblogs.com/aadzj/p/15312220.html