Spring简单入门
2020-01-12 20:15
99 查看
Spring简单入门
初始Spring
什么是Spring
-
Spring 是一个开源框架。
-
Spring 致力于javaEE(企业级应用)应用的解决方案,而不是仅仅某一层(是雨露均沾)。
-
Spring是企业级开发的“一站式”的轻量级框架
为什么是轻量级框架?
-
非侵入式编程:非侵入式的代码则没有过多的依赖,可以很方便的迁移到其他地方。但是与用户代码互动的方式可能就比较复杂 (无需继承框架提供的任何类)。
-
JavaEE分三层开发
数据库(BLL):mybatis,hibernate - 业务逻辑层(BIZ)
- 表现层:servlet,springmvc,strut2
Spring的优点
- 低侵入 / 低耦合 (降低组件之间的耦合度,实现软件各层之间的解耦)
- 声明式事务管理(基于切面和惯例)
- 方便集成其他框架(如MyBatis、Hibernate)
- 降低 Java 开发难度
Spring IoC的基本入门开发
IoC:控制反转
- 读作“反转控制”,不是什么技术,而是一种设计思想,就是将原本在程序中手动创建对象的控制权,交由Spring框架来管理。
Spring IoC开发步骤
-
导jar包
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.9.RELEASE</version> </dependency> <!-- spring-beans --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.1.9.RELEASE</version> </dependency> <!-- spring-core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.1.9.RELEASE</version> </dependency> <!-- spring-expression --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>5.1.9.RELEASE</version> </dependency>
-
编写程序
在 Packge【pojo】下新建一个【Greeting】类:
public class Greeting { //说话的人 private String person = "Nobody"; //说话的内容 private String words = "nothing"; //无参构造函数 public Greeting() { } public Greeting(String person, String words) { this.person = person; this.words = words; } //输出的方法 public void sayGreeting(){ System.out.println(person+"说:"+words+"\""); } //get和set方法 public String getPerson() { return person; } public void setPerson(String person) { this.person = person; } public String getWords() { return words; } public void setWords(String words) { this.words = words; } }
-
在xml文件中配置Greeting对象
<?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,该bean的id是greeting,class指定bean实例的实现类--> <bean id="greeting" class="pojo.Greeting"> <!--property元素用来指定需要容器注入的属性,words属性需要容器注入,但是必须拥有set方法--> <property name="words"> <value>世界很大</value> </property> <property name="person"> <value>天天</value> </property> </bean> </beans>
-
测试
public class TestGreeting { @Test public void kneTest(){ //通过ClassPathXmlApplicationContext实例化Spring的上下文 ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml"); //通过ApplicationContext的getBean()方法,根据Id来获取Bean的实例 Greeting greeting = (Greeting)context.getBean("greeting"); //调用输出方法 greeting.sayGreeting(); } }
-
输出:天天说:世界很大"
ApplicationContext容器
最常被使用的 ApplicationContext 接口实现:
-
ApplicationContext是一个接口,负责接收Spring配置文件,管理对象的加载,维护Bean对象与Bean对象之间的依赖关系,负责Bean的生命周期
Spring AOP(面向切面编程)
AOP(面向切面编程)
-
什么是AOP,简单地说就是在不改变原程序的基础上为代码增加新的功能,对代码段进行增强处理。
-
AOP的一些基本概念
切面(Aspect):一个模块的横切逻辑(或称横切关注点),可能会很切多个对象 - 连接点(Joi Point):程序执行中的某给具体的执行点
- 增强处理(Advice):切面在某个特定连接点上执行代码逻辑
- 切入点(Pointcut):对连接点的特征进行描述
- 织入(Weaving):将增强处理连接到应用程序中的类型或对象上的过程
使用Spring AOP实现输出
-
导jar文件
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>5.1.9.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/aopalliance/aopalliance --> <dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> <version>1.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.4</version> </dependency>
-
编写增强类OrderLogger
public class OrderLogger { private static final Logger log = Logger.getLogger(OrderLogger.class); //前置增强 public void preposition(JoinPoint jp){ log.info("调用"+jp.getSignature().getDeclaringType()+"类"+" 的"+jp.getSignature().getName()+"方法,参数"+ Arrays.toString(jp.getArgs())); } //后置增强(正常运行) public void postposition(JoinPoint jp,Object restetr){ log.info("调用"+jp.getSignature().getDeclaringType()+"类"+" 的"+jp.getSignature().getName()+"方法,方法返回值"+restetr ); } }
注意:
getSignature()方法返回被代理的目标方法 - getTarget()方法可以得到被代理的目标对象
配置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"<!--aop相关配置--> xmlns:p="http://www.springframework.org/schema/p" 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<!--aop相关配置--> http://www.springframework.org/schema/aop/spring-aop.xsd<!--aop相关配置--> http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <bean id="orderLogger" class="utils.OrderLogger"></bean> <aop:config> <!--定义一个切入点表达式,并命名为:pointcut--> <aop:pointcut id="pointcut" expression="execution(* biz.impl.*.*(..))"/> <aop:aspect ref="orderLogger"> <!--前置增强--> <aop:before method="preposition" pointcut-ref="pointcut"/> </aop:aspect> </aop:config> </beans>
注意:
execution是切入点指示符,它的括号是一个切入点的表达式,可以配置需要切入增强处理的方法的特征,切入点表示式支持模糊匹配。
-
public * addNewUser(entity.User):"*" 表示匹配所有类型的返回值
执行代码
几种增强类型
-
异常抛出增强
public class OrderLogger { private static final Logger log = Logger.getLogger(OrderLogger.class); //异常抛出增强 public void afterThrowing(JoinPoint jp,RuntimeException e){ log.info(jp.getSignature().getName()+"方法,方法异常"+e ); } }
<!--引用包含增强的方法的Bean--> <aop:aspect ref="orderLogger"> <aop:after-returning method="afterThrowing" pointcut-ref="pointcut" throwing="e" ></aop:after-returning> </aop:aspect>
-
最终增强
public class OrderLogger { private static final Logger log = Logger.getLogger(OrderLogger.class); //异常抛出增强 public void afterLogger(JoinPoint jp){ log.info(jp.getSignature().getName()+"方法执行" ); } }
<!--引用包含增强的方法的Bean--> <aop:aspect ref="orderLogger"> <aop:after method="afterLogger" pointcut-ref="pointcut" ></aop:afte> </aop:aspect>
-
环绕增强
public class AfterLogger { private static final Logger log = Logger.getLogger(ErrorLogger.class); public Object aroundLogger(ProceedingJoinPoint jp) throws Throwable { log.info("调用"+jp.getTarget()+" 的"+jp.getSignature().getName()+"方法。方法入参:"+ Arrays.toString(jp.getArgs())); Object result = jp.proceed();//执行目标方法并获得其返回值 try { log.info("调用 "+jp.getTarget()+" 的"+jp.getSignature().getName()+" 方法。方法返回值"+result); return result; } catch (Throwable throwable) { log.error(jp.getSignature().getName()+" 方法发生异常: "+ throwable); throwable.printStackTrace(); }finally { log.info(jp.getSignature().getName()+" 方法结束执行。"); } return result; } }
<!--引用包含增强的方法的Bean--> <aop:aspect ref="orderLogger"> <aop:around method="aroundLogger" pointcut-ref="pointcut" ></aop:around> </aop:aspect>
使用注解实现IoC的配置
-
使用注解实现Bean组件装配
@Service("orderBiz") public class OrderBizImpl implements OrderBiz { @Autowired private OrderMapper mapper ; @Resource private OrderDeteilMapper orderDeteilMapper; @Override public List<Order> selectLists() { return mapper.selectLists(); } @Override @Transactional(propagation = Propagation.SUPPORTS) public int add(Order order, OrderDeteil orderDeteil) { int rst = mapper.add(order); orderDeteil.setOrderId(order.getId()); rst = orderDeteilMapper.add(orderDeteil); return rst; } public OrderMapper getMapper() { return mapper; } public void setMapper(OrderMapper mapper) { this.mapper = mapper; } public OrderDeteilMapper getOrderDeteilMapper() { return orderDeteilMapper; } public void setOrderDeteilMapper(OrderDeteilMapper orderDeteilMapper) { this.orderDeteilMapper = orderDeteilMapper; } }
注意:
@Repositoey:用于标注DAO类 - @Service:用于标注业务类
- @Controller:用于标注控制器类
- @Autowired:采用按类型匹配的方式为属性自动装配合适的依赖对象,既容器会查找和属性类型相匹配的Bean组件,并自动为属性注入。
加载注解定义的Bean
<?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" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" 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 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--开启注解--> <context:component-scan base-package="action,biz"> </context:component-scan> </beans>
MyBatis与Spring的整合
Spring整合MyBatis的准备工作
-
导jar包
<!-- spring-beans --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.1.9.RELEASE</version> </dependency> <!--spring-core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.1.9.RELEASE</version> </dependency> <!-- spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.9.RELEASE</version> </dependency> <!-- spring-expression --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>5.1.9.RELEASE</version> </dependency> <!-- commons-logging --> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <!--aspectj weaver--> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.4</version> </dependency> <!-- spring-cn.aop --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>5.1.9.RELEASE</version> </dependency> <!--spring-jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.1.7.RELEASE</version> </dependency> <!--spring-tx --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.1.7.RELEASE</version> </dependency> <!--aopalliance --> <dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> <version>1.0</version> </dependency> <!--mysql jar--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.17</version> </dependency> <!-- mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency> <!--log4j--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- mybatis-spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.1</version> </dependency> <!-- commons-dbcp2 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>2.7.0</version> </dependency> <!-- commons-pool2 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.7.0</version> </dependency>
-
创建实体类
public class Classes { private Integer id; private String name;//名称 public Classes() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } }
-
创建数据访问接口
public interface ClassesMapper { List<Classes> selectList(); }
-
配置SQL映射文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="mapper.ClassesMapper"> <select id="selectList" resultType="pojo.Classes"> select id,name from classes where 1 = 1 </select> </mapper>
-
配置MyBatis配置文件
<?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> <mappers> <mapper resource="mapper/ClassesMapper.xml"></mapper> </mappers> </configuration>
实现Spring对MyBatis的整合
-
配置数据源
导jar包
<!-- commons-dbcp2 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>2.7.0</version> </dependency> <!-- commons-pool2 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.7.0</version> </dependency>
-
配置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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p" 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="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close"> <!-- BasicDataSource提供了close()方法关闭数据源,所以必须设定destroy-method=”close”属性, 以便Spring容器关闭时,数据源能够正常关闭;销毁方法调用close(),是将连接关闭,并不是真正的把资源销毁 --> <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property> <property name="url"> <!-- 千万注意,这里不能换行 --> <value><![CDATA[jdbc:mysql://127.0.0.1:3306/stusys?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8]]></value> </property> <property name="username" value="root"></property> <property name="password" value="root"></property> </bean> </beans>
-
配置SqlSessionFactoryBean
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--引用数据源组件--> <property name="dataSource" ref="dataSource"/> <!--引用MyBatis配置文件中的配置--> <property name="configLocation" value="classpath:mybatis-config.xml"/> </bean>
-
测试
注入映射器实现
-
配置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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p" 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="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close"> <!-- BasicDataSource提供了close()方法关闭数据源,所以必须设定destroy-method=”close”属性, 以便Spring容器关闭时,数据源能够正常关闭;销毁方法调用close(),是将连接关闭,并不是真正的把资源销毁 --> <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property> <property name="url"> <!-- 千万注意,这里不能换行 --> <value><![CDATA[jdbc:mysql://127.0.0.1:3306/stusys?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8]]></value> </property> <property name="username" value="root"></property> <property name="password" value="root"></property> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:mybatis-config.xml"/> </bean> <!--单个单个类的扫描 --> <bean id="classesMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="mapper.classes.ClassesMapper" /> <property name="sqlSessionFactory" ref="sqlSessionFactory" /> </bean> <!--使用MapperScannerConfigurer注入映射器--> <!-- 扫描整个包下的所有:命名规则就是首字母改成小写 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="mapper" /> </bean> </beans>
为业务层添加声明事务
-
配置声明事务
<?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" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" 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 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--配置数据源--> <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close"> <!-- BasicDataSource提供了close()方法关闭数据源,所以必须设定destroy-method=”close”属性, 以便Spring容器关闭时,数据源能够正常关闭;销毁方法调用close(),是将连接关闭,并不是真正的把资源销毁 --> <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property> <property name="url"> <!-- 千万注意,这里不能换行 --> <value><![CDATA[jdbc:mysql://127.0.0.1:3306/easybuy?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8]]></value> </property> <property name="username" value="root"></property> <property name="password" value="root"></property> </bean> <!--事务的切面--> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!--切入点--> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="add*" propagation="SUPPORTS"/> </tx:attributes> </tx:advice> <!--配置SqlSessionFactoryBean--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--引用数据源组件--> <property name="dataSource" ref="dataSource"/> <!--引用MyBatis配置文件中的配置--> <property name="configLocation" value="classpath:mybatis-confing.xml"/> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="mapper" /> </bean> <!--开启注解--> <context:component-scan base-package="action,biz"> </context:component-scan> </beans>
注意:
add*,中的※代表通配符
事务类型
-
PROPAGATION_REQUIRED :表示如果当前事务存在,则支持当前事务。否则,会启动一个新的事务。默认事务类型。
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- 最简单的spring-mvc入门示例,绝对原创
- JSP的那些事儿(9)----最简单的Spring入门
- spring-data-jpa快速入门(二)——简单查询
- spring整合mybatis(入门级简单教程1)--在spring中配置c3p0,并成功测试
- spring-boot之一:简单入门
- Eclipse Spring Roo 简单入门教程
- Spring Data Jpa简单入门
- spring cloud简单入门
- 【java开发系列】—— spring简单入门示例
- spring简单入门
- 基于注解的Spring MVC+Hiberntae简单入门
- 最简单的spring-mvc入门示例,绝对原创
- spring整合mybatis(入门级简单教程2)
- Spring简单入门实例
- 【java开发系列】—— spring简单入门示例
- activeMQ整合springboot简单入门
- spring简单入门示例
- Spring 简单入门实例
- spring简单入门示例
- spring整合redis demo 简单入门