当前位置: 首页 > news >正文

建筑专业网站广州关于进一步优化

建筑专业网站,广州关于进一步优化,河北seo网站开发,做ppt一般收费多少2-Spring 文章目录 2-Spring项目源码地址Spring概述Spring特点#xff08;优点#xff09;Spring相关学习网站基于Maven的Spring框架导入Spring的组成及拓展 Spring-IOC--原型理解IOC-原型--示例开发示例-常规开发示例-Set函数#xff08;IOC原型#xff09;开发示例-对比思…2-Spring 文章目录 2-Spring项目源码地址Spring概述Spring特点优点Spring相关学习网站基于Maven的Spring框架导入Spring的组成及拓展 Spring-IOC--原型理解IOC-原型--示例开发示例-常规开发示例-Set函数IOC原型开发示例-对比思考 IOC-本质--概念IOC-实现--Spring中以IOC方式管理bean示例--HelloWorld理解 IOC-修改--Spring实现IOC Spring-IOC--IOC Containerbean--创建无参构造创建带参构造创建 bean--配置别名配置import-多xml配置文件管理 DI-依赖注入-基本注入方式注入方式-Set注入详解-N种常见类型数据注入注入方式-p标签、c标签注入 Bean--作用域Bean--自动装配--Autowire案例常规case手动装配Spring-自动装配-XMLbyNameSpring-自动装配-XMLbyTypeSpring-自动装配-注解-AutowiredSpring-自动装配-注解-QualifierSpring-自动装配-注解-ResourceSpring-三种注解方法Autowired、Qualifier、Resource总结Spring-自动装配-注解-Component、Value、scopeSpring-自动装配-XML与注解的对比Java-自动装配-注解-Configuration、ComponentScan AOP代理模式理解AOP基本概念什么是AOPAop在Spring中的相关概念 Spring中实现AOP示例中通用的代码XML配置--通过Spring API来实现XML配置--通过自定义类来实现注解--通过自定义类来实现 Spring事务事务四大特性acidSpring中的事务**编程式事务管理**声明式事务管理 Spring声明式事务处理导入约束定义事务管理器配置事务通知spring事务传播特性配置AOP织入事务测试代码 项目源码地址 GitHubhttps://github.com/Web-Learn-GSF/Java_Learn_Examples父工程Java_Framework_Spring Spring概述 Spring特点优点 Spring是一个开源免费的框架容器Spring是一个轻量级的框架非侵入式的控制反转IOC面向切面AOP【IOC和AOP是Spring学习的重点】对事务支持对框架支持 Spring是一个轻量级的控制反转IOC和面向切面AOP的容器【框架】 Spring相关学习网站 中文文档https://www.docs4dev.com/docs/zh/spring-framework/5.1.3.RELEASE/reference/core.html#beans 官方文档https://spring.io/projects/spring-framework#learn 源码下载https://repo.spring.io/ui/native/milestone/org/springframework/spring/ GitHubhttps://github.com/spring-projects/spring-framework/releases 基于Maven的Spring框架导入 访问https://mvnrepository.com/搜索Spring xml配置导入 !-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -- dependencygroupIdorg.springframework/groupIdartifactIdspring-webmvc/artifactIdversion6.0.13/version /dependency导入该依赖通过依赖传递性会自动导入spring-aop、spring-beans、spring-context、spring-core、spring-expression、spring-web Spring的组成及拓展 七大组成模块 模块作用Spring Core核心容器提供 Spring 框架的基本功能。核心容器的主要组件是 BeanFactory它是工厂模式的实现。BeanFactory 使用控制反转IOC 模式将应用程序的配置和依赖性规范与实际的应用程序代码分开Spring ContextSpring 上下文是一个配置文件向 Spring 框架提供上下文信息。Spring 上下文包括企业服务例如 JNDI、EJB、电子邮件、国际化、校验和调度功能Spring AOP通过配置管理特性Spring AOP 模块直接将面向切面的编程功能 集成到了 Spring 框架中。所以可以很容易地使 Spring 框架管理任何支持 AOP的对象。Spring AOP 模块为基于 Spring 的应用程序中的对象提供了事务管理服务。通过使用 Spring AOP不用依赖组件就可以将声明性事务管理集成到应用程序中Spring DAOJDBC DAO 抽象层提供了有意义的异常层次结构可用该结构来管理异常处理和不同数据库供应商抛出的错误消息。异常层次结构简化了错误处理并且极大地降低了需要编写的异常代码数量例如打开和关闭连接。Spring DAO 的面向 JDBC 的异常遵从通用的 DAO 异常层次结构Spring ORMSpring 框架插入了若干个 ORM 框架从而提供了 ORM 的对象关系工具其中包括 JDO、Hibernate 和 iBatis SQL Map。所有这些都遵从 Spring 的通用事务和 DAO 异常层次结构Spring WebWeb 上下文模块建立在应用程序上下文模块之上为基于 Web 的应用程序提供了上下文。所以Spring 框架支持与 Jakarta Struts 的集成。Web 模块还简化了处理多部分请求以及将请求参数绑定到域对象的工作Spring MVCMVC 框架是一个全功能的构建 Web 应用程序的 MVC 实现。通过策略接口MVC 框架变成为高度可配置的MVC 容纳了大量视图技术其中包括 JSP、Velocity、Tiles、iText 和 POI Spring拓展Spring Boot 和 Spring Cloud Spring BootSpring Cloud是 Spring 的一套快速配置脚手架可以基于Spring Boot 快速开发单个微服务基于Spring Boot实现的专注于快速、方便集成的单个微服务个体关注全局的服务治理框架使用了约束优于配置的理念很多集成方案已经帮你选择好了能不配置就不配置很大的一部分是基于Spring Boot来实现Spring Boot可以离开Spring Cloud独立使用开发项目但是Spring Cloud离不开Spring Boot属于依赖的关系起承上启下的作用如果要学习SpringCloud必须要学习SpringBoot Spring-IOC–原型理解 IOC-原型–示例 开发示例-常规 三层结构 底层源码Dao接口、实现 业务端Service业务接口、业务实现 客户端Client调用 源码实现 底层源码UserDao接口 public interface UserDao {public void getUser(); }底层源码UserDao实现 public class UserDaoImpl implements UserDao {Overridepublic void getUser() {System.out.println(Dao获取用户数据);} }业务端UserService接口 public interface UserService {public void getUser(); }业务端UserService实现 public class UserServiceImpl implements UserService {private UserDao userDao new UserDaoImpl();Overridepublic void getUser() {userDao.getUser();} }用户端测试 public class UserTest {Testpublic void test(){UserService service new UserServiceImpl();service.getUser();} }若增加一个源码实现 UserSql public interface UserSql {public void getUser(); }public class UserSqlImpl implements UserSql {Overridepublic void getUser() {System.out.println(Sql获取用户数据);} }业务端UserService实现代码更改 public class UserServiceImpl implements UserService {// 原内容private UserDao userDao new UserDaoImpl();// 修改后的内容private UserDao userDao new UserSqlImpl();Overridepublic void getUser() {userDao.getUser();} }针对常规开发模式每增加一个源码实现都需要对服务端实现的代码进行更改非常麻烦。代码耦合性太高 如何解决利用Set函数 开发示例-Set函数IOC原型 保持其他内容不变修改服务端实现类的代码内容 public class UserServiceImpl implements UserService {private UserDao userDao;// 利用set实现public void setUserDao(UserDao userDao) {this.userDao userDao;}Overridepublic void getUser() {userDao.getUser();} }客户端代码实现 Test public void test(){UserServiceImpl service new UserServiceImpl();// Dao实现service.setUserDao( new UserDaoMySqlImpl() );service.getUser();//Sql实现service.setUserDao( new UserSqlImpl() );service.getUser(); }可以看到针对新的源码实现不再需要修改业务端逻辑仅是在客户端通过传入不同的业务端实现对象即可完成更改 开发示例-对比思考 常规IOC原型对象创建主动权在程序对象创建主动权在调用者对象是写死的更改实现对象就需要更改业务端代码对象是通过接口动态接收的调用者给什么就实现什么 IOC-本质–概念 IoC(Inversion of Control控制反转) 是一种设计思想DI(Dependency Injection依赖注入) 是实现IoC的一种方法 在Spring中实现控制反转的是IoC容器其实现方法是依赖注入Dependency InjectionDI 没有IoC的程序中 我们使用面向对象编程对象的创建与对象间的依赖关系完全硬编码在程序中对象的创建由程序自己控制控制反转后将对象的创建转移给第三方实现解耦。 IOC-实现–Spring中以IOC方式管理bean 示例–HelloWorld 源码准备 HelloWorld.java package com.learn.Hello;public class HelloWorld {private String name;public String getName() {return name;}public void setName(String name) {this.name name;}public void show(){System.out.println(Hello, name );} }beans.xml ?xml version1.0 encodingUTF-8? beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd!--bean就是java对象 , 由Spring创建和管理--bean idhello classcom.learn.Hello.HelloWorldproperty namename valueSpring//bean/beansHelloWorldTest.java import com.learn.Hello.HelloWorld; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;public class HelloWorldTest {Testpublic void test(){//解析beans.xml文件, 生成管理相应的Bean对象ApplicationContext context new ClassPathXmlApplicationContext(beans.xml);//getBean : 参数即为spring配置文件中bean的id .HelloWorld hello (HelloWorld) context.getBean(hello);hello.show();} }理解 思考 Hello 对象是谁创建的?由Spring创建的Hello 对象的属性是怎么设置的?由Spring容器设置的根据set方法 IOC理解 这个过程就叫控制反转 控制 : 传统应用程序的对象是由程序本身控制创建的 , 使用Spring后 , 对象是由Spring来创建的反转程序本身不创建对象 , 而变成被动的接收对象 依赖注入 依赖相关属性信息配置在xml文件中注入通过set方法由Spring读取xml文件并创建对象 IOC-修改–Spring实现IOC 新建xml配置文件 ?xml version1.0 encodingUTF-8? beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd!--底层源码实现--bean idMysqlImpl classcom.learn.dao.UserMySqlImpl/bean idDaoImpl classcom.learn.dao.UserDaoImpl/!--业务端代码实现--bean idServiceImpl classcom.learn.service.UserServiceImpl!--注意: 这里的name并不是属性, 而是UserServiceImpl实现类里面setUserDao方法中set后面的那部分, 其中首字母要小写--!--该方法的参数是引用另外一个bean, 这里不能用value而是用ref--property nameuserDao refOracleImpl//bean/beans修改客户端的测试代码 // 原内容 Test public void test(){UserServiceImpl service new UserServiceImpl();// Dao实现service.setUserDao( new UserDaoMySqlImpl() );service.getUser();//Sql实现service.setUserDao( new UserSqlImpl() );service.getUser(); }// 修改后内容 Test public void test(){ApplicationContext context new ClassPathXmlApplicationContext(beans.xml);UserServiceImpl serviceImpl (UserServiceImpl) context.getBean(ServiceImpl);serviceImpl.getUser(); }后续所有的操作均不需要去改动业务端统一由xml配置文件修改即可 Spring-IOC–IOC Container bean–创建 无参构造创建 无参构造属性的写入本质是set方式注入 public class User {private String name;public User() {System.out.println(user无参构造方法);}public void setName(String name) {this.name name;}public void show(){System.out.println(name name );}}?xml version1.0 encodingUTF-8? beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdbean iduser classcom.kuang.pojo.Userproperty namename valuekuangshen//bean/beansTest public void test(){ApplicationContext context new ClassPathXmlApplicationContext(beans.xml);//在执行getBean的时候, user已经创建好了, 通过无参构造User user (User) context.getBean(user);//调用对象的方法 .user.show(); }带参构造创建 带参构造属性的写入本质是构造器方式注入 public class UserT {private String name;public UserT(String name) {this.name name;}public void setName(String name) {this.name name;}public void show(){System.out.println(name name );}}?xml version1.0 encodingUTF-8? beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd!-- 第一种根据index参数下标设置 --bean iduserT classcom.kuang.pojo.UserT!-- index指构造方法 , 下标从0开始 --constructor-arg index0 valuekuangshen2//bean!-- 第二种根据参数名字设置 --bean iduserT classcom.kuang.pojo.UserT!-- name指参数名 --constructor-arg namename valuekuangshen2//bean!-- 第三种根据参数类型设置 --bean iduserT classcom.kuang.pojo.UserTconstructor-arg typejava.lang.String valuekuangshen2//bean/beans第三种方法使用较为限制。当多个属性具有相同的类型就没法用了 type基本数据类型就写int、double…type引用数据类型就按照上边示例来写就行 Test public void testT(){ApplicationContext context new ClassPathXmlApplicationContext(beans.xml);// 在配置文件加载的时候。其中管理的对象都已经初始化了UserT user (UserT) context.getBean(userT);user.show(); }bean–配置 别名配置 alias标签配置 !--设置别名在获取Bean的时候可以使用别名获取原名依旧可用-- alias nameuserT aliasuserNew/bean标签中的name属性配置 !--bean就是java对象,由Spring创建和管理--!--id 是bean的标识符,要唯一,如果没有配置id,name就是默认标识符如果配置id,又配置了name,那么name是别名name可以设置多个别名,可以用逗号,分号,空格隔开如果不配置id和name,可以根据applicationContext.getBean(.class)获取对象;class是bean的全限定名包名类名 -- bean idhello namehello2 h2,h3;h4 classcom.kuang.pojo.Helloproperty namename valueSpring/ /beanimport-多xml配置文件管理 !--在主配置文件中引入其他配置文件-- import resource{path}/beans.xml/DI-依赖注入-基本 依赖注入Dependency Injection,DI 依赖 : 指Bean对象的创建依赖于容器.注入 : 指Bean对象所依赖的资源 , 由容器来设置和装配. 注入方式 注入方式解释Set注入针对无参构造的bean构造器注入针对带参构造的beanp标签注入本质还是set注入需要有无参构造方法c标签注入本质是构造器注入需要有带参构造方法 注入方式-Set注入详解-N种常见类型数据注入 要求被注入的属性 , 必须有set方法 , set方法的方法名由set 属性首字母大写 如果属性是boolean类型 , 没有set方法 , 是 is.【有疑问IDEA 2023创建出来的boolean属性有set方法但是没有get方法】 常见属性类型的set方式注入 package com.kuang.pojo;import java.util.List;import java.util.Map;import java.util.Properties;import java.util.Set;public class Student {// 属性private String name;private Address address;private String[] books;private ListString hobbys;private MapString,String card;private SetString games;private String wife;private Properties info;// set方法public void setName(String name) {this.name name;}public void setAddress(Address address) {this.address address;}public void setBooks(String[] books) {this.books books;}public void setHobbys(ListString hobbys) {this.hobbys hobbys;}public void setCard(MapString, String card) {this.card card;}public void setGames(SetString games) {this.games games;}public void setWife(String wife) {this.wife wife;}public void setInfo(Properties info) {this.info info;}public void show(){System.out.println(name name ,address address.getAddress() ,books);for (String book:books){System.out.print(book\t);}System.out.println(\n爱好:hobbys);System.out.println(card:card);System.out.println(games:games);System.out.println(wife:wife);System.out.println(info:info);}}常量注入 bean idstudent classcom.kuang.pojo.Studentproperty namename value小明/ /beanbean注入 常规ref引入 bean idaddr classcom.kuang.pojo.Addressproperty nameaddress value重庆//beanbean idstudent classcom.kuang.pojo.Studentproperty namename value小明/property nameaddress refaddr//beaninner bean引入 需要要求该inner bean 不会被其他地方引用即该inner bean随着outer bean的创建而创建 bean idouter class...!-- instead of using a reference to a target bean, simply define the target bean inline --property nametargetbean classcom.example.Person !-- this is the inner bean --property namename valueFiona Apple/property nameage value25//bean/property /bean数组注入 bean idstudent classcom.kuang.pojo.Studentproperty namename value小明/property nameaddress refaddr/property namebooksarrayvalue西游记/valuevalue红楼梦/valuevalue水浒传/value/array/property/beanList注入 property namehobbyslistvalue听歌/valuevalue看电影/valuevalue爬山/value/list/propertyMap注入 property namecardmapentry key中国邮政 value456456456465456/entry key建设 value1456682255511//map/property集合set注入 property namegamessetvalueLOL/valuevalueBOB/valuevalueCOC/value/set/propertyNull注入 property namewifenull//propertyProperties注入 property nameinfopropsprop key学号20190604/propprop key性别男/propprop key姓名小明/prop/props/property注入方式-p标签、c标签注入 ?xml version1.0 encodingUTF-8? beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlns:phttp://www.springframework.org/schema/pxsi:schemaLocationhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd!--需要在头部导入p标签约束上述倒数第三行--bean iduser classcom.kuang.pojo.User p:name狂神 p:age18/?xml version1.0 encodingUTF-8? beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlns:chttp://www.springframework.org/schema/cxsi:schemaLocationhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd!--需要在头部导入c标签约束上述倒数第三行--bean iduser classcom.kuang.pojo.User c:name狂神 c:age18/Bean–作用域 在Spring中那些组成应用程序的主体及由Spring IoC容器所管理的对象被称之为bean。 简单地讲bean就是由IoC容器初始化、装配及管理的对象。 类别说明singleton默认在Spring IOC容器中仅存一个Bean实例以单例方式存在prototype每次从容器中调用Bean时都返回一个新的实例即每次调用getBean()时相当于执行new XXXBean()request每次HTTP请求都会创建一个新的Bean该作用域仅适用于WebApplicationContext环境session同一个Http Session共享一个Bean不同Session使用不同Bean仅适用于WebApplicationContext环境 Singleton 创建容器时就同时自动创建一个bean对象不管是否调用实例已经存在了 bean idServiceImpl classcn.csdn.service.ServiceImpl scopesingletonPrototype 创建容器的时候没有初始化当获取bean的时候才会去创建一个对象 bean idaccount classcom.foo.DefaultAccount scopeprototype/ 或者bean idaccount classcom.foo.DefaultAccount singletonfalse/ Request 每个HTTP请求都会有各自的bean实例它们依据某个bean定义创建而成 bean idloginAction classcn.csdn.LoginAction scoperequest/Session 在一个HTTP Session中一个bean定义对应一个实例 bean iduserPreferences classcom.foo.UserPreferences scopesession/Bean–自动装配–Autowire 自动装配是Spring满足bean依赖的一种方式 不需要手动给与属性Sping会在上下文中自动寻找并自动给bean装配属性 案例 一个人有名字和两个宠物分别是猫和狗都会叫猫会miao狗会wang分析 3个bean狗、猫、人狗的bean“叫”方法猫的bean“叫“方法人的bean三个属性名字、狗、猫 public class Cat {public void shout() {System.out.println(miao~);} }public class Dog {public void shout() {System.out.println(wang~);} }package com.learn.Hello;public class People {private Cat cat;private Dog dog;private String name;public Cat getCat() {return cat;}public void setCat(Cat cat) {this.cat cat;}public Dog getDog() {return dog;}public void setDog(Dog dog) {this.dog dog;}public String getName() {return name;}public void setName(String name) {this.name name;} }常规case手动装配 ?xml version1.0 encodingUTF-8? beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd!--猫--bean idcat classcom.learn.Hello.Cat/!--狗--bean iddog classcom.learn.Hello.Dog/!--人--bean idPeople classcom.learn.Hello.Peopleproperty namename value张三/property namedog refdog/property namecat refcat//bean/beansSpring-自动装配-XMLbyName 会自动在上下文中查找id跟自己属性值一样的bean ?xml version1.0 encodingUTF-8? beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd!--猫--bean idcat classcom.learn.Hello.Cat//bean!--狗--bean iddog classcom.learn.Hello.Dog//bean!--人--bean idPeople classcom.learn.Hello.People autowirebyNameproperty namename value张三//bean/beans将cat的id改为catXXX报错 Spring-自动装配-XMLbyType 会根据属性的类型自动去上下文中找对应属性的bean这就要求属性全局唯一不然idea会报错不让用该种装配方法 ?xml version1.0 encodingUTF-8? beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd!--猫--bean idcat classcom.learn.Hello.Cat/bean!--狗--bean iddog classcom.learn.Hello.Dog/bean!--人--bean idPeople classcom.learn.Hello.People autowirebyTypeproperty namename value张三//bean/beanscase1再注册一个cat对象bean id取名为cat2报错case2将cat和dog的id删除掉运行正常【因为是通过Type进行自动装配的不影响】 Spring-自动装配-注解-Autowired 该方式可以不需要bean中有set方法 准备 XML文件中引入新的约束并开启支持注解 ?xml version1.0 encodingUTF-8? beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlns:contexthttp://www.springframework.org/schema/contextxsi:schemaLocationhttp://www.springframework.org/schema/beanshttps://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttps://www.springframework.org/schema/context/spring-context.xsdcontext:annotation-config/!--正常写入bean信息--/beans测试 package com.learn.Hello;import org.springframework.beans.factory.annotation.Autowired;public class People {Autowiredprivate Cat cat;Autowiredprivate Dog dog;private String name;public Cat getCat() {return cat;}public Dog getDog() {return dog;}public String getName() {return name;}public void setName(String name) {this.name name;} }?xml version1.0 encodingUTF-8? beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlns:contexthttp://www.springframework.org/schema/contextxsi:schemaLocationhttp://www.springframework.org/schema/beanshttps://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttps://www.springframework.org/schema/context/spring-context.xsdcontext:annotation-config/!--猫--bean idcat classcom.learn.Hello.Cat/!--狗--bean iddog classcom.learn.Hello.Dog/!--人--!--人的属性默认给为null--bean idpeople classcom.learn.Hello.People//beans删除掉People类中的set方法加入注解测试依旧成功 Autowired参数 public class People {Autowired(requiredfalse)private Cat cat; }requiredfalse即对象可以为null该参数默认为true即注解的属性不可以为null Spring-自动装配-注解-Qualifier Autowired是根据类型Type自动装配的当根据类型无法完成装配时加上Qualifier则可以根据byName的方式自动装配Qualifier不能单独使用需要和Autowired配套使用 bean iddog1 classcom.kuang.pojo.Dog/ bean iddog2 classcom.kuang.pojo.Dog/ bean idcat1 classcom.kuang.pojo.Cat/ bean idcat2 classcom.kuang.pojo.Cat/package com.learn.Hello;import org.springframework.beans.factory.annotation.Autowired;public class People {Autowired()Qualifier(value cat2)private Cat cat;AutowiredQualifier(value dog2)private Dog dog;private String name;public Cat getCat() {return cat;}public Dog getDog() {return dog;}public String getName() {return name;}public void setName(String name) {this.name name;} }Spring-自动装配-注解-Resource 不是Spring框架的注解而是Java自带的注解 Resource如有参数指定name属性先按该属性进行byName方式查找装配其次再进行默认的byName方式进行装配 如果以上都不成功则按byType的方式自动装配都不成功则报异常 bean iddog classcom.kuang.pojo.Dog/ bean idcat1 classcom.kuang.pojo.Cat/ bean idcat2 classcom.kuang.pojo.Cat/bean iduser classcom.kuang.pojo.User/public class User {//如果允许对象为null设置required false, 默认为trueResource(name cat2)private Cat cat;Resourceprivate Dog dog;private String str; }补充 jdk的版本影响注解Resource的使用 解决方法1使用jdk8开发 解决方法2在maven中的pom.xml从新导入一个javax.annotation的jar包 dependencygroupIdjavax.annotation/groupIdartifactIdjavax.annotation-api/artifactIdversion1.2/version /dependencySpring-三种注解方法Autowired、Qualifier、Resource总结 注解方法解释Autowired默认按类型装配默认情况下必须要求依赖对象必须存在如果要允许null 值可以设置它的required属性为falseAutowired(requiredfalse)Qualifier按照name装配配合Autowired使用当Autowired无法按照类型装配的时候配合Qualifier按照name装配Resource默认按照名称进行装配名称可以通过name属性进行指定如果没有指定name属性当注解写在字段上时默认取字段名进行按照名称查找如果注解写在setter方法上默认取属性名进行装配当找不到与名称匹配的bean时才按照类型进行装配。但是需要注意的是如果name属性一旦指定就只会按照名称进行装配 Spring-自动装配-注解-Component、Value、scope 从基于xml文件的bean标签实现依赖注入到通过Component注解形式实现注入 准备工作 xml文件中加入注解扫描包通过指定注解扫描包可以让注解的类完成注入 扫描的是类上的注解而不是方法上的注解 ?xml version1.0 encodingUTF-8? beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlns:contexthttp://www.springframework.org/schema/contextxsi:schemaLocationhttp://www.springframework.org/schema/beanshttps://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttps://www.springframework.org/schema/context/spring-context.xsd!--指定注解扫描包--context:component-scan base-packagecom.kuang.pojo/context:annotation-config//beansAOP包的引入 !-- 该引入可以引入spring有关的好几个包包括AOP -- dependencygroupIdorg.springframework/groupIdartifactIdspring-webmvc/artifactIdversion6.0.13/version /dependency指定包下编写类并加入注解 Component(user) // 相当于配置文件中 bean iduser classcom.spring.learn.User/ Scope(prototype) // 相当于配置文件中 bean iduser classcom.spring.learn.User scopeprototype/ public class User {Value(张三) // 写在字段上相当于配置文件中 property namename value张三/public String name;public int age;Value(18) // 写在set方法上相当于配置文件中 property nameage value张三/public void setAge(int age) {this.age age;} }测试 Test public void test(){ApplicationContext applicationContext new ClassPathXmlApplicationContext(beans.xml);User user (User) applicationContext.getBean(user);System.out.println(user.name); }Component衍生注解 为了更好的进行分层Spring可以使用其它三个注解功能跟Component都一样 注解应用场景Controller在Controller层进行注入时使用的注解Service在Service层进行注入时使用的注解Repository在Dao层进行注入时使用的注解 Spring-自动装配-XML与注解的对比 XML注解可以适用任何场景 结构清晰维护方便注解只能对特定的类生效开发简单方便 推荐使用XML管理bean注解完成属性注入写在字段上或写在方法上的注解当使用XML管理bean的时候就不用扫描了扫描是为了扫描类上的注解 Java-自动装配-注解-Configuration、ComponentScan JavaConfig 原来是 Spring 的一个子项目它通过 Java 类的方式提供 Bean 的定义信息在 Spring4 的版本 JavaConfig 已正式成为 Spring4 的核心功能 从原先的xml文件配置依赖注入到通过Java类配置依赖注入 实体类 Component // 将这个类标注为Spring的一个组件放到容器中 public class Dog {public String name dog; }Config包起到beans.xml文件的作用 Configuration //代表这是一个配置类 ComponentScan(com.learn.Dog) // 代表要扫描Dog包下的类带有注解的类将被放进Spring中管理 public class MyConfig {Bean //通过方法注册一个bean这里的返回值就Bean的类型方法名就是bean的idpublic Dog getDog(){return new Dog();} }ComponentScan 和 Configuration 一般配合一起使用 如果没有ComponentScan会默认扫描Configuration所注解的类所在的包 但为什么要配合使用 如果类中用了ControllerRepositoryService, Component四大注解标识之一了那么如果不加上ComponentScanSpring就不会自动扫描类上的四大注解中的任何一个那么四大注解下的类就不会被Spring扫描到更不会装入Spring容器中因此配置的四大注解就失去了作用 测试 Test public void test2(){ApplicationContext applicationContext new AnnotationConfigApplicationContext(MyConfig.class);Dog dog (Dog) applicationContext.getBean(getDog);System.out.println(dog.name); }AOP 代理模式理解 AOP的底层实现就是动态代理学习AOP之前先了解动态代理 参考文章https://blog.csdn.net/qq_45445505/article/details/134038354 AOP基本概念 先写下来不求甚解了边学边回顾吧 什么是AOP AOPAspect Oriented Programming意为面向切面编程通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。 AOP是OOP的延续是软件开发中的一个热点也是Spring框架中的一个重要内容是函数式编程的一种衍生范型。 利用AOP可以对业务逻辑的各个部分进行隔离从而使得业务逻辑各部分之间的耦合度降低提高程序的可重用性同时提高了开发的效率。 Aop在Spring中的相关概念 作用提供声明式事务允许用户自定义切面 相关名词 名词解释横切关注点跨越应用程序多个模块的方法或功能。即是与我们业务逻辑无关的但是我们需要关注的部分就是横切关注点。如日志 , 安全 , 缓存 , 事务等等 …切面ASPECT横切关注点 被模块化 的特殊对象。即它是一个类通知Advice切面必须要完成的工作。即它是类中的一个方法目标Target被通知对象代理Proxy向目标对象应用通知之后创建的对象切入点PointCut切面通知 执行的 “地点”的定义连接点JointPoint与切入点匹配的执行点 Spring中支持的5种Advice类型 通知类型连接点实现接口前置通知方法前org.springframework.aop.MethodBeforeAdvice后置通知方法后org.springframework.aop.AfterReturningAdvice环绕通知方法前后org.springframework.aop.MethodInterceptor异常抛出通知方法抛出异常org.springframework.aop.ThrowsAdvice引介通知类中增加新的方法属性org.springframework.aop.IntroductionInterceptor Spring中实现AOP 示例中通用的代码 业务层 package GSF.Example.Service;public interface UserService {public void add();public void delete();public void update();public void search(); }package GSF.Example.Service;public class UserServiceImpl implements UserService {Overridepublic void add() {System.out.println(执行User的add方法);}Overridepublic void delete() {System.out.println(执行User的delete方法);}Overridepublic void update() {System.out.println(执行User的update方法);}Overridepublic void search() {System.out.println(执行User的search方法);} }测试 package GSF.Example.Test;import GSF.Example.Service.UserService; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;public class MyTest {Testpublic void Test(){ApplicationContext context new ClassPathXmlApplicationContext(applicationContext.xml);UserService userService context.getBean(userService, UserService.class);userService.add(); // userService.delete(); // userService.update(); // userService.search();} }XML配置–通过Spring API来实现 项目名称 Java_Framework_SpringAOP_1_Xml_SpringAPI 前置通知示例 package GSF.Example.Log;import org.springframework.aop.MethodBeforeAdvice;import java.lang.reflect.Method;public class LogBeforeMethod implements MethodBeforeAdvice {/***** param method 要执行的目标对象UserServiceImpl的方法* param args 被调用的方法的参数* param target 目标对象UserServiceImpl* throws Throwable*/Overridepublic void before(Method method, Object[] args, Object target) throws Throwable {System.out.println(AOP前置通知 在 target.getClass().getName() 的 method.getName() 方法调用前执行。目标对象-方法-参数都可以获取到);} }后置通知 package GSF.Example.Log;import org.springframework.aop.AfterReturningAdvice;import java.lang.reflect.Method;public class LogAfterMethod implements AfterReturningAdvice {Overridepublic void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {System.out.println(AOP后置通知 在 target.getClass().getName() 的 method.getName() 方法调用后执行。目标对象-方法-参数都可以获取到);} }XML配置 ?xml version1.0 encodingUTF-8? beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlns:aophttp://www.springframework.org/schema/aopxsi:schemaLocationhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsd!-- 注册bean --bean iduserService classGSF.Example.Service.UserServiceImpl /bean idlogBefore classGSF.Example.Log.LogBeforeMethod /bean idlogAfter classGSF.Example.Log.LogAfterMethod/!-- Aop的设置--aop:config!-- 切入点--aop:pointcut idpointcut expressionexecution(* GSF.Example.Service.UserServiceImpl.*(..))/!-- 执行前置通知--aop:advisor advice-reflogBefore pointcut-refpointcut /aop:advisor advice-reflogAfter pointcut-refpointcut //aop:config /beansXML配置–通过自定义类来实现 项目名称 Java_Framework_SpringAOP_2_Xml_CustomClass package GSF.Example.Log;public class CustomLogClass {public void before(){System.out.println(---------基于XML自定义类方式实现前置通知:方法执行前---------);}public void after(){System.out.println(---------基于XML自定义类方式实现后置通知:方法执行前---------);} } ?xml version1.0 encodingUTF-8? beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlns:aophttp://www.springframework.org/schema/aopxsi:schemaLocationhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsd!-- 注册bean --bean iduserService classGSF.Example.Service.UserServiceImpl /bean idcustomLogClass classGSF.Example.Log.CustomLogClass /!--Aop的设置--aop:config!-- 切入点--aop:aspect refcustomLogClassaop:pointcut idpointcut expressionexecution(* GSF.Example.Service.UserServiceImpl.*(..))/aop:before methodbefore pointcut-refpointcut/aop:after methodafter pointcut-refpointcut //aop:aspect/aop:config /beans注解–通过自定义类来实现 项目名称 Java_Framework_SpringAOP_3_Xml_Annotation package GSF.Example.Log;import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before;Aspect public class AnnotationClass {Before(execution(* GSF.Example.Service.UserServiceImpl.*(..)))public void before(){System.out.println(---------基于注解方式实现前置通知:方法执行前---------);}After(execution(* GSF.Example.Service.UserServiceImpl.*(..)))public void after(){System.out.println(---------基于注解方式实现后置通知方法执行后---------);}Around(execution(* GSF.Example.Service.UserServiceImpl.*(..)))public void around(ProceedingJoinPoint jp) throws Throwable{System.out.println(环绕通知环绕前);System.out.println(jp.getSignature());// 执行目标方法Object proceed jp.proceed();System.out.println(proceed);System.out.println(环绕通知环绕后);} }XML配置 ?xml version1.0 encodingUTF-8? beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlns:aophttp://www.springframework.org/schema/aopxsi:schemaLocationhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsd!-- 注册bean --bean iduserService classGSF.Example.Service.UserServiceImpl /bean idannotationPointcut classGSF.Example.Log.AnnotationClass /!-- 自动代理 --aop:aspectj-autoproxy//beansSpring事务 事务四大特性acid 特性解释原子性atomicity事务是原子性操作由一系列动作组成事务的原子性确保动作要么全部完成要么完全不起作用一致性consistency一旦所有事务动作完成事务就要被提交。数据和资源处于一种满足业务规则的一致性状态中隔离性isolation可能多个事务会同时处理相同的数据因此每个事务都应该与其他事务隔离开来防止数据损坏持久性durability事务一旦完成无论系统发生什么错误结果都不会受到影响。通常情况下事务的结果被写到持久化存储器中 Spring中的事务 Spring在不同的事务管理API之上定义了一个抽象层使得开发人员不必了解底层的事务管理API就可以使用Spring的事务管理机制。 Spring支持编程式事务管理和声明式的事务管理 编程式事务管理 将事务管理代码嵌到业务方法中来控制事务的提交和回滚缺点必须在每个事务操作业务逻辑中包含额外的事务管理代码 声明式事务管理 一般情况下比编程式事务好用。将事务管理代码从业务方法中分离出来以声明的方式来实现事务管理。将事务管理作为横切关注点通过aop方法模块化。Spring中通过Spring AOP框架支持声明式事务管理。 Spring声明式事务处理 项目名称 Java_Framework_SpringTransaction_Spring_Mybatis 导入约束 ?xml version1.0 encodingUTF-8? beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlns:aophttp://www.springframework.org/schema/aopxmlns:txhttp://www.springframework.org/schema/txxsi:schemaLocationhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsdtx有关的 定义事务管理器 无论使用Spring的哪种事务管理策略编程式或者声明式事务管理器都是必须的。 就是Spring的核心事务管理抽象管理封装了一组独立于技术的方法 !-- JDBC事务 -- bean idtransactionManagerclassorg.springframework.jdbc.datasource.DataSourceTransactionManagerproperty namedataSource refdataSource / /bean配置事务通知 !--配置事务通知-- tx:advice idtxAdvice transaction-managertransactionManagertx:attributes!--配置哪些方法使用什么样的事务,配置事务的传播特性--tx:method nameadd propagationREQUIRED/tx:method namedelete propagationREQUIRED/tx:method nameupdate propagationREQUIRED/tx:method namesearch* propagationREQUIRED/tx:method nameget read-onlytrue/tx:method name* propagationREQUIRED//tx:attributes /tx:advicespring事务传播特性 事务传播行为就是多个事务方法相互调用时事务如何在这些方法间传播spring支持的事务传播行为 参数含义propagation_requierd默认如果当前没有事务就新建一个事务如果已存在一个事务中加入到这个事务中这是最常见的选择propagation_supports支持当前事务如果没有当前事务就以非事务方法执行propagation_mandatory使用当前事务如果没有当前事务就抛出异常propagation_required_new新建事务如果当前存在事务把当前事务挂起propagation_not_supported以非事务方式执行操作如果当前存在事务就把当前事务挂起propagation_never以非事务方式执行操作如果当前事务存在则抛出异常propagation_nested如果当前存在事务则在嵌套事务内执行。如果当前没有事务则执行与propagation_required类似的操作 配置AOP织入事务 !--配置aop织入事务-- aop:configaop:pointcut idtxPointcut expressionexecution(* com.kuang.dao.*.*(..))/aop:advisor advice-reftxAdvice pointcut-reftxPointcut/ /aop:config测试代码 人为制造错误写错deletes delete iddeleteUser parameterTypeintdeletes from learn_mybatis.user where id#{id}; /deleteUserDaoImpl多个方法放一起 package GSF.Example.Dao;import GSF.Example.Pojo.User; import org.mybatis.spring.support.SqlSessionDaoSupport;import java.util.List; import java.util.Map;public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao{Overridepublic User getUserById(int id) {User user new User(id, 测试事务, 123235);UserDao mapper getSqlSession().getMapper(UserDao.class);mapper.addUser(user);mapper.deleteUser(id);return mapper.getUserById(id);}Overridepublic int addUser(User user) {return getSqlSession().getMapper(UserDao.class).addUser(user);}Overridepublic int deleteUser(int id) {return getSqlSession().getMapper(UserDao.class).deleteUser(id);}}测试代码 package GSF.Example.Dao;import GSF.Example.Pojo.User; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;public class UserTest {Testpublic void TestTransaction(){ApplicationContext context new ClassPathXmlApplicationContext(spring-dao.xml);UserDao userDaoImpl (UserDao) context.getBean(userDaoImpl);User userById userDaoImpl.getUserById(28);System.out.println(userById);} }结果分析 未开启事务新增数据成功并没有删除数据开启事务新增数据失败
http://www.yutouwan.com/news/158804/

相关文章:

  • 网站投票系统 js网上购物系统的设计与实现论文
  • 济南免费网站制作有源码怎么做app
  • 株洲做网站的公司wordpress搬家后页面空白
  • 360网站图标怎么做的wordpress博客下载插件
  • 长沙手机网站制作南京网络推广公司排名
  • 成都市网站建设费用及企业网上写文章用什么软件
  • 做宠物网站心得网站建立
  • 怎么做北京赛车网站新乡个人网站建设
  • 伊犁网站制作网站后台图片传不上去怎么办
  • 中信建设有限责任公司世界排名宝应seo
  • 网站开发招标文件范本做食品的采购员常用网站
  • 承德网站推广适合注册公司的名字大全
  • 个人网站可以备案了吗苏州seo推广优化
  • 网站建设方案进行工期安排移动互联网平台有哪些
  • 微信网站结构嘉定网站设计怎么样
  • 网站 备案网站python做的网站漏洞
  • 山东省城乡住房建设厅网站个人缴纳养老保险
  • 平台网站开发的税率诸暨哪些公司可以制作网站
  • 如何做网站关键词排名网站建设都会用到哪些建站工具
  • 安庆网站建设公司教师做网站赚钱
  • 在天极网做网站有效果吗网络营销现状分析
  • 网站的风格设计有哪些苏州定制型网站建设
  • 英文网站制作公司哪家好淄博做网站公司
  • 青岛网站建设工作室做冻品的网站
  • WordPress网站小程序做外贸需要哪些网站有哪些
  • 工商局网上注册公司seo智能优化公司
  • 高新公司网站建设电话杭州企业网站搭建
  • 英文网站外链查询网站开发合同受托方
  • 制作简历模板网站先做网站还是先备案
  • 免费企业网站模板 phpwordpress原创主题简单