网站模板做网站良品铺子网站规划和建设

web/2025/9/27 20:01:49/文章来源:
网站模板做网站,良品铺子网站规划和建设,百度aipage智能建站系统,网站建设的目的只是开展网络营销Java SSM4——Spring Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器#xff08;框架#xff09; Spring的优势 方便解耦#xff0c;简化开发 Spring就是一个容器#xff0c;可以将所有对象创建和关系维护交给Spring管理 什么是耦合度#xff1f;对象之间的关…Java SSM4——Spring Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架 Spring的优势 方便解耦简化开发 Spring就是一个容器可以将所有对象创建和关系维护交给Spring管理 什么是耦合度对象之间的关系通常说当一个模块(对象)更改时也需要更改其他模块(对象)这就是耦合耦合度过高会使代码的维护成本增加。要尽量解耦 AOP编程的支持 Spring提供面向切面编程方便实现程序进行权限拦截运行监控等功能 声明式事务的支持 通过配置完成事务的管理无需手动编程 方便测试降低JavaEE API的使用 Spring对Junit4支持可以使用注解测试 方便集成各种优秀框架 不排除各种优秀的开源框架内部提供了对各种优秀框架的直接支持 1、IOC Inverse Of Control控制反转配置文件解除硬编码反射解除编译器依赖 控制在java中指的是对象的控制权限创建、销毁反转指的是对象控制权由原来 由开发者在类中手动控制交由Spring管理 2、AOP Aspect Oriented Programming面向切面编程动态代理方法增强 3、快速入门 默认为maven项目 3.1、导入依赖 dependencies!--spring--dependencygroupIdorg.springframework/groupIdartifactIdspring-context/artifactIdversion5.3.9/version/dependencydependencygroupIdjunit/groupIdartifactIdjunit/artifactIdversion4.13/versionscopetest/scope/dependency /dependencies3.2、Spring核心配置文件 如无特殊需求我们默认spring核心配置文件名为applicationContent.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.xsdbean idHelloSpring classclub.winkto.bean.HelloSpring/bean /beans3.3、书写简单的类 public class HelloSpring {public void hellospring(){System.out.println(hello spring!);} }3.4、测试 Test public void test(){ClassPathXmlApplicationContext classPathXmlApplicationContext new ClassPathXmlApplicationContext(applicationContent.xml);HelloSpring hellospring classPathXmlApplicationContext.getBean(hellospring, HelloSpring.class);hellospring.hellospring(); }4、Spring API BeanFactory也可以完成ApplicationContext完成的事情为什么我们要选择ApplicationContext BeanFactory在第一次调用getBean()方法时创建指定对象的实例 ApplicationContext在spring容器启动时加载并创建所有对象的实例 4.1、常用实现类 ClassPathXmlApplicationContext 它是从类的根路径下加载配置文件 推荐使用这种FileSystemXmlApplicationContext 它是从磁盘路径上加载配置文件配置文件可以在磁盘的任意位置AnnotationConfigApplicationContext 当使用注解配置容器对象时需要使用此类来创建 spring 容器它用来读取注解 5、Spring IOC 5.1、bean 5.1.1、基础使用 bean id class/beanidBean实例在Spring容器中的唯一标识classBean的全限定名默认情况下它调用的是类中的 无参构造函数如果没有无参构造函数则不能创建成功 5.1.2、scope属性 bean id class scope/beansingleton单例默认 对象创建当应用加载创建容器时对象就被创建了对象运行只要容器在对象一直活着对象销毁当应用卸载销毁容器时对象就被销毁了 prototype多例 对象创建当使用对象时创建新的对象实例对象运行只要对象在使用中就一直活着对象销毁当对象长时间不用时被 Java 的垃圾回收器回收了 5.1.3、生命周期的配置 bean id class包名.类名 init-method指定class的方法 destroy-method指定class的方法/beaninit-method指定类中的初始化方法名称destroy-method指定类中销毁方法名称 5.1.4、Bean实例化的三种方式 5.1.4.1、构造器实例化 spring容器通过bean对应的默认的构造函数来实例化bean。 上述即是 5.1.4.2、 静态工厂方式实例化 bean id class包名.类名 factory-method指定class的方法 /首先创建一个静态工厂类在类中定义一个静态方法创建实例。 静态工厂类及静态方法 public class MyUserDaoFactory{//静态方法返回UserDaoImpl的实例对象public static UserDaoImpl createUserDao{return new UserDaoImpl();} }xml配置文件 ?xml version1.0 encodingUTF-8? !DOCTYPE beans PUBLIC -//SPRING//DTD BEAN//ENhttp://www.springframework.org/dtd/spring-beans.dtd beans!-- 将指定对象配置给spring让spring创建其实例 --bean iduserDao classcom.ioc.MyUserDaoFactory factory-methodcreateUserDao/ /beans5.1.4.3、 实例工厂方式实例化 bean id工厂类id class包名.类名/ bean id factory-bean工厂类id factorymethod工厂类id里的方法/该种方式的工厂类中不再使用静态方法创建Bean实例而是采用直接创建Bean实例的方式。同时在配置文件中需要实例化的Bean也不是通过class属性直接指向其实例化的类而是通过factory-bean属性配置一个实例工厂然后使用factory-method属性确定使用工厂中哪个方法。 工厂类方法 public class MyBeanFactory{public MyBeanFactory(){System.out.println(this is a bean factory);}public UserDaoImpl createUserDao(){return new UserDaoImpl();} }xml配置文件 ?xml version1.0 encodingUTF-8? !DOCTYPE beans PUBLIC -//SPRING//DTD BEAN//ENhttp://www.springframework.org/dtd/spring-beans.dtd beans!-- 配置工厂 --bean idmyBeanFactory classcom.ioc.MyBeanFactory/!-- 使用factory-bean属性配置一个实例工厂使用factory-method属性确定工厂中的哪个方法 --bean iduserDao factory-beanmyBeanFactory factory-methodcreateUserDao/ /beans主函数 public class Client {public static void main(String[] args) {// TODO Auto-generated method stub//此处定义xml文件放置的位置为src目录下的com/xml目录下String path com/xml/bean.xml;ApplicationContext application new ClassPathXmlApplicationContext(path);UserDaoImpl userDao (UserDaoImpl) application.getBean(userDao);userDao.sayHello(); //调用UserDaoImpl类的sayHello方法} }5.1.5、别名 5.1.5.1、alias标签 alias namehello aliashello1/alias 5.1.5.2、bean标签name属性 bean idHelloSpring namehello2 h2,h3;h4 classclub.winkto.bean.HelloSpring/bean可写多个别名分隔符为空格逗号分号均可 5.2、依赖注入DI Spring 框架核心 IOC 的具体实现 5.2.1、构造方法 mapper public interface WinktoMapper {void mapper(); }public class WinktoMapperImpl implements WinktoMapper {public void mapper() {System.out.println(假装自己有了数据库查询);} }service public interface WinktoService {void service(); }public class WinktoServiceImpl implements WinktoService {private int a;private WinktoMapperImpl winktoMapper;private Object[] arrays;private List list;private MapString,Object map;private Set set;private Properties properties;public WinktoServiceImpl(int a, WinktoMapperImpl winktoMapper, Object[] arrays, List list, MapString, Object map, Set set, Properties properties) {this.a a;this.winktoMapper winktoMapper;this.arrays arrays;this.list list;this.map map;this.set set;this.properties properties;}public void service() {System.out.println(假装自己开启了事务);winktoMapper.mapper();System.out.println();System.out.println(toString());System.out.println();System.out.println(假装自己提交了事务);}Overridepublic String toString() {return WinktoServiceImpl{ a a , winktoMapper winktoMapper , arrays arrays , list list , map map , set set , properties properties };} }aplicationContent.xml bean idwinktoMapper classclub.winkto.mapper.WinktoMapperImpl/beanbean idwinktoService classclub.winkto.service.WinktoServiceImpl!--constructor-arg index0 value12/constructor-arg--!--constructor-arg index1 refwinktoMapper/constructor-arg--!--constructor-arg index2--!-- array--!-- value1/value--!-- ref beanwinktoMapper/ref--!-- /array--!--/constructor-arg--!--constructor-arg index3--!-- list--!-- value2/value--!-- ref beanwinktoMapper/ref--!-- /list--!--/constructor-arg--!--constructor-arg index4--!-- map--!-- entry keyname valuezhangsan/entry--!-- entry keyservice value-refwinktoMapper/entry--!-- /map--!--/constructor-arg--!--constructor-arg index5--!-- set--!-- value3/value--!-- ref beanwinktoMapper/ref--!-- /set--!--/constructor-arg--!--constructor-arg index6--!-- props--!-- prop keynamezhangsan/prop--!-- /props--!--/constructor-arg--constructor-arg namea value12/constructor-argconstructor-arg namewinktoMapper refwinktoMapper/constructor-argconstructor-arg namearraysarrayvalue1/valueref beanwinktoMapper/ref/array/constructor-argconstructor-arg namelistlistvalue2/valueref beanwinktoMapper/ref/list/constructor-argconstructor-arg namemapmapentry keyname valuezhangsan/entryentry keyservice value-refwinktoMapper/entry/map/constructor-argconstructor-arg namesetsetvalue3/valueref beanwinktoMapper/ref/set/constructor-argconstructor-arg namepropertiespropsprop keynamezhangsan/prop/props/constructor-arg/bean /beans测试 Test public void test(){ClassPathXmlApplicationContext classPathXmlApplicationContext new ClassPathXmlApplicationContext(applicationContent.xml);WinktoService winktoService classPathXmlApplicationContext.getBean(winktoService, WinktoService.class);winktoService.service(); }5.2.2、set mapper public interface WinktoMapper {void mapper(); }public class WinktoMapperImpl implements WinktoMapper {public void mapper() {System.out.println(假装自己有了数据库查询);} }service public interface WinktoService {void service(); }public class WinktoServiceImpl implements WinktoService {private int a;private WinktoMapperImpl winktoMapper;private Object[] arrays;private List list;private MapString,Object map;private Set set;private Properties properties;public int getA() {return a;}public void setA(int a) {this.a a;}public WinktoMapperImpl getWinktoMapper() {return winktoMapper;}public void setWinktoMapper(WinktoMapperImpl winktoMapper) {this.winktoMapper winktoMapper;}public Object[] getArrayList() {return arrays;}public void setArrayList(Object[] arrays) {this.arrays arrays;}public List getList() {return list;}public void setList(List list) {this.list list;}public MapString, Object getMap() {return map;}public void setMap(MapString, Object map) {this.map map;}public Set getSet() {return set;}public void setSet(Set set) {this.set set;}public Properties getProperties() {return properties;}public void setProperties(Properties properties) {this.properties properties;}public void service() {System.out.println(假装自己开启了事务);winktoMapper.mapper();System.out.println();System.out.println(toString());System.out.println();System.out.println(假装自己提交了事务);}Overridepublic String toString() {return WinktoServiceImpl{ a a , winktoMapper winktoMapper , arrays arrays , list list , map map , set set , properties properties };} }aplicationContent.xml bean idwinktoMapper classclub.winkto.mapper.WinktoMapperImpl /bean bean idwinktoService classclub.winkto.service.WinktoServiceImplproperty namea value12/propertyproperty namewinktoMapper refwinktoMapper/propertyproperty namearrayListarrayvalue1/valueref beanwinktoMapper/ref/array/propertyproperty namelistlistvalue2/valueref beanwinktoMapper/ref/list/propertyproperty namemapmapentry keyname valuezhangsan/entryentry keyservice value-refwinktoMapper/entry/map/propertyproperty namesetsetvalue3/valueref beanwinktoMapper/ref/set/propertyproperty namepropertiespropsprop keynamezhangsan/prop/props/property /bean测试 Test public void test(){ClassPathXmlApplicationContext classPathXmlApplicationContext new ClassPathXmlApplicationContext(applicationContent.xml);WinktoService winktoService classPathXmlApplicationContext.getBean(winktoService, WinktoService.class);winktoService.service(); }5.2.3、p命名空间简单示范 导入约束 xmlns:phttp://www.springframework.org/schema/p mapper public interface WinktoMapper {void mapper(); } public class WinktoMapperImpl implements WinktoMapper {public void mapper() {System.out.println(假装自己有了数据库查询);} }service public interface WinktoService {void service(); }public class WinktoServiceImpl implements WinktoService {private WinktoMapperImpl winktoMapper;public WinktoMapperImpl getWinktoMapper() {return winktoMapper;}public void setWinktoMapper(WinktoMapperImpl winktoMapper) {this.winktoMapper winktoMapper;}public void service() {System.out.println(假装自己开启了事务);winktoMapper.mapper();System.out.println(假装自己提交了事务);} }aplicationContent.xml 对于bean引用用p:xxx-ref否则使用p:xxx bean idwinktoMapper classclub.winkto.mapper.WinktoMapperImpl /bean bean idwinktoService classclub.winkto.service.WinktoServiceImpl p:winktoMapper-refwinktoMapper /bean测试 Test public void test(){ClassPathXmlApplicationContext classPathXmlApplicationContext new ClassPathXmlApplicationContext(applicationContent.xml);WinktoService winktoService classPathXmlApplicationContext.getBean(winktoService, WinktoService.class);winktoService.service(); } 5.2.4、c命名空间简单示范 导入约束 xmlns:chttp://www.springframework.org/schema/c mapper public interface WinktoMapper {void mapper(); } public class WinktoMapperImpl implements WinktoMapper {public void mapper() {System.out.println(假装自己有了数据库查询);} } service public interface WinktoService {void service(); } public class WinktoServiceImpl implements WinktoService {private WinktoMapperImpl winktoMapper;public WinktoMapperImpl getWinktoMapper() {return winktoMapper;}public void setWinktoMapper(WinktoMapperImpl winktoMapper) {this.winktoMapper winktoMapper;}public void service() {System.out.println(假装自己开启了事务);winktoMapper.mapper();System.out.println(假装自己提交了事务);} } aplicationContent.xml 对于bean引用用c:xxx-ref否则使用c:xxxc命名空间可以额外使用c:_0-ref bean idwinktoMapper classclub.winkto.mapper.WinktoMapperImpl /bean !--bean idwinktoService classclub.winkto.service.WinktoServiceImpl c:winktoMapper-refwinktoMapper-- !--/bean-- bean idwinktoService classclub.winkto.service.WinktoServiceImpl c:_0-refwinktoMapper /bean 测试 Test public void test(){ClassPathXmlApplicationContext classPathXmlApplicationContext new ClassPathXmlApplicationContext(applicationContent.xml);WinktoService winktoService classPathXmlApplicationContext.getBean(winktoService, WinktoService.class);winktoService.service(); } 5.3、配置文件模块化 5.3.1、配置文件并列 ClassPathXmlApplicationContext classPathXmlApplicationContext new ClassPathXmlApplicationContext(applicationContent.xml,beans.xml); 5.3.2、主从配置文件 在applicationContent.xml导入beans.xml import resourcebeans.xml/ 6、Spring注解开发IOC部分 Spring是轻代码而重配置的框架配置比较繁重影响开发效率所以注解开发是一种趋势注解代 替xml配置文件可以简化配置提高开发效率 开启注解扫描 !--注解的组件扫描-- context:component-scan base-packageclub.winkto/context:component-scan 6.1、注册bean 注解说明Component使用在类上用于实例化BeanController使用在web层类上用于实例化BeanService使用在service层类上用于实例化BeanRepository使用在dao层类上用于实例化Bean 6.2、依赖注入 注解说明Autowired使用在字段上用于根据类型依赖注入先根据type类型不唯一根据name自动装配的Qualifier结合Autowired一起使用,根据名称进行依赖注入Resource相当于AutowiredQualifier按照名称进行注入很少用且jdk11在spring核心包不包含此注解Value注入普通属性也可以注入spring配置文件里的其他普通属性使用${}上面三个注入引用类型 6.3、初始销毁 注解说明PostConstruct使用在方法上标注该方法是Bean的初始化方法PreDestroy使用在方法上标注该方法是Bean的销毁方法 6.4、新注解 注解说明Configuration用于指定当前类是一个Spring 配置类当创建容器时会从该类上加载注解Bean使用在方法上标注将该方法的返回值存储到 Spring 容器中PropertySource用于加载 properties 文件中的配置ComponentScan用于指定 Spring 在初始化容器时要扫描的包Import用于导入其他配置类 6.5、注解快速入门 mapper public interface WinktoMapper {void mapper(); } Repository(winktoMapper) public class WinktoMapperImpl implements WinktoMapper {public void mapper() {System.out.println(假装自己有了数据库查询);} } service public interface WinktoService {void service(); } Service(winktoService) public class WinktoServiceImpl implements WinktoService {Value(12)private int a;Autowiredprivate WinktoMapperImpl winktoMapper;public WinktoServiceImpl() {}public WinktoServiceImpl(int a, WinktoMapperImpl winktoMapper) {this.a a;this.winktoMapper winktoMapper;}public int getA() {return a;}public void setA(int a) {this.a a;}public WinktoMapperImpl getWinktoMapper() {return winktoMapper;}public void setWinktoMapper(WinktoMapperImpl winktoMapper) {this.winktoMapper winktoMapper;}public void service() {System.out.println(假装自己开启了事务);winktoMapper.mapper();System.out.println();System.out.println(toString());System.out.println();System.out.println(假装自己提交了事务);}Overridepublic String toString() {return WinktoServiceImpl{ a a , winktoMapper winktoMapper };} } aplicationContent.xml ?xml version1.0 encodingUTF-8? beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlns:phttp://www.springframework.org/schema/pxmlns:chttp://www.springframework.org/schema/cxmlns:contexthttp://www.springframework.org/schema/contextxsi:schemaLocationhttp://www.springframework.org/schema/beanshttp://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-packageclub.winkto/context:component-scan /beans 测试 Test public void test(){ClassPathXmlApplicationContext classPathXmlApplicationContext new ClassPathXmlApplicationContext(applicationContent.xml);WinktoService winktoService classPathXmlApplicationContext.getBean(winktoService, WinktoService.class);winktoService.service(); } 6.6、纯注解开发 导入依赖 dependencies!--spring--dependencygroupIdorg.springframework/groupIdartifactIdspring-context/artifactIdversion5.3.9/version/dependencydependencygroupIdjunit/groupIdartifactIdjunit/artifactIdversion4.13/versionscopetest/scope/dependencydependencygroupIdcom.fasterxml.jackson.core/groupIdartifactIdjackson-databind/artifactIdversion2.9.6/version/dependency /dependencies mapper public interface WinktoMapper {void mapper(); } Repository(winktoMapper) public class WinktoMapperImpl implements WinktoMapper {Value(${name})private String name;public void mapper() {System.out.println(name);System.out.println(假装自己有了数据库查询);} } service public interface WinktoService {void service(); } Service(winktoService) public class WinktoServiceImpl implements WinktoService {Value(12)private int a;Autowiredprivate WinktoMapperImpl winktoMapper;public WinktoServiceImpl() {}public WinktoServiceImpl(int a, WinktoMapperImpl winktoMapper) {this.a a;this.winktoMapper winktoMapper;}public int getA() {return a;}public void setA(int a) {this.a a;}public WinktoMapperImpl getWinktoMapper() {return winktoMapper;}public void setWinktoMapper(WinktoMapperImpl winktoMapper) {this.winktoMapper winktoMapper;}public void service() {System.out.println(假装自己开启了事务);winktoMapper.mapper();System.out.println();System.out.println(toString());System.out.println();System.out.println(假装自己提交了事务);}Overridepublic String toString() {return WinktoServiceImpl{ a a , winktoMapper winktoMapper };} } config Configuration PropertySource(classpath:database.properties) public class WinktoMapperConfig {Value(${name})private String name; } Configuration ComponentScan(club.winkto) Import(WinktoMapperConfig.class) public class WinktoConfig {Beanpublic ObjectMapper objectMapper(){return new ObjectMapper();} } 测试 Test public void test() throws JsonProcessingException {AnnotationConfigApplicationContext annotationConfigApplicationContext new AnnotationConfigApplicationContext(WinktoConfig.class);WinktoService winktoService annotationConfigApplicationContext.getBean(winktoService, WinktoService.class);ObjectMapper objectMapper annotationConfigApplicationContext.getBean(objectMapper, ObjectMapper.class);System.out.println(objectMapper.writeValueAsString(winktoService));winktoService.service(); } 6.7、Spring整合junit 导入依赖 dependencies!--spring--dependencygroupIdorg.springframework/groupIdartifactIdspring-context/artifactIdversion5.3.9/version/dependency!--spring-test--dependencygroupIdorg.springframework/groupIdartifactIdspring-test/artifactIdversion5.3.9/versionscopetest/scope/dependencydependencygroupIdjunit/groupIdartifactIdjunit/artifactIdversion4.13/versionscopetest/scope/dependencydependencygroupIdcom.fasterxml.jackson.core/groupIdartifactIdjackson-databind/artifactIdversion2.9.6/version/dependency /dependencies 修改Test类 RunWith(SpringJUnit4ClassRunner.class) //ContextConfiguration(value {classpath:applicationContext.xml}) ContextConfiguration(classes {WinktoConfig.class}) public class MyTest {Autowiredprivate WinktoService winktoService;Autowiredprivate ObjectMapper objectMapper;Testpublic void test() throws JsonProcessingException {System.out.println(objectMapper.writeValueAsString(winktoService));winktoService.service();} } 7、动态代理 7.1、JDK动态代理 基于接口的动态代理技术利用拦截器必须实现invocationHandler加上反射机制生成 一个代理接口的匿名类在调用具体方法前调用InvokeHandler来处理从而实现方法增强 7.2.1、JDK动态代理实现 service public interface CRUD {void select();void insert();void update();void delete(); } Service public class CRUDService implements CRUD {public void select() {System.out.println(假装自己执行了select);}public void insert() {System.out.println(假装自己执行了insert);}public void update() {System.out.println(假装自己执行了update);}public void delete() {System.out.println(假装自己执行了delete);} } config Configuration ComponentScan(cn.winkto) public class WinktoConfig {Bean(objectMapper)public ObjectMapper getObjectMapper(){return new ObjectMapper();} } 代理 Component public class JDKProxy {public Object proxy(final CRUDService crudService){return Proxy.newProxyInstance(crudService.getClass().getClassLoader(), crudService.getClass().getInterfaces(), new InvocationHandler() {public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {System.out.println(代理前);Object invoke method.invoke(crudService, args);System.out.println(代理后);return invoke;}});} } 测试 RunWith(SpringJUnit4ClassRunner.class) ContextConfiguration(classes {WinktoConfig.class}) public class MyTest {Autowiredprivate JDKProxy jdkProxy;Autowiredprivate CRUDService crudService;Testpublic void test(){CRUD proxy (CRUD) jdkProxy.proxy(crudService);proxy.select();} } 7.2、CGLIB代理 基于父类的动态代理技术动态生成一个要代理的子类子类重写要代理的类的所有不是 final的方法。在子类中采用方法拦截技术拦截所有的父类方法的调用顺势织入横切逻辑对方法进行 增强 7.2.1、CGLIB代理的实现 service public interface CRUD {void select();void insert();void update();void delete(); } Service public class CRUDService implements CRUD {public void select() {System.out.println(假装自己执行了select);}public void insert() {System.out.println(假装自己执行了insert);}public void update() {System.out.println(假装自己执行了update);}public void delete() {System.out.println(假装自己执行了delete);} } config Configuration ComponentScan(cn.winkto) public class WinktoConfig {Bean(objectMapper)public ObjectMapper getObjectMapper(){return new ObjectMapper();} } 代理 Component public class CglibProxy {public Object proxy(final CRUDService crudService){return Enhancer.create(crudService.getClass(), new MethodInterceptor() {public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {System.out.println(代理前);Object invoke method.invoke(crudService, objects);System.out.println(代理后);return invoke;}});} } 测试 RunWith(SpringJUnit4ClassRunner.class) ContextConfiguration(classes {WinktoConfig.class}) public class MyTest {Autowiredprivate JDKProxy jdkProxy;Autowiredprivate CglibProxy cglibProxy;Autowiredprivate CRUDService crudService;Testpublic void test1(){CRUD proxy (CRUD) cglibProxy.proxy(crudService);proxy.select();} } 8、Spring AOP AOP 是 OOP面向对象编程 的延续是软件开发中的一个热点也是Spring框架中的一个重要内容利用AOP可以对业务逻辑的各个部分进行隔离从而使得业务逻辑各部分之间的耦合度降低提高程序的可重用性同时提高了开发的效率 在程序运行期间在不修改源码的情况下对方法进行功能增强逻辑清晰开发核心业务的时候不必关注增强业务的代码减少重复代码提高开发效率便于后期维护 8.1、Aop术语解释 Target目标对象代理的目标对象Proxy 代理一个类被 AOP 织入增强后就产生一个结果代理类Joinpoint连接点所谓连接点是指那些可以被拦截到的点。在spring中这些点指的是方法因为 spring只支持方法类型的连接点Pointcut切入点所谓切入点是指我们要对哪些 Joinpoint 进行拦截的定义Advice通知/ 增强所谓通知是指拦截到 Joinpoint 之后所要做的事情就是通知 分类前置通知、后置通知、异常通知、最终通知、环绕通知Aspect切面是切入点和通知引介的结合Weaving织入是指把增强应用到目标对象来创建新的代理对象的过程。spring采用动态代理织 入而AspectJ采用编译期织入和类装载期织入 8.2、Aop快速入门 导入依赖 dependencies!--spring--dependencygroupIdorg.springframework/groupIdartifactIdspring-context/artifactIdversion5.3.9/version/dependency!--spring-test--dependencygroupIdorg.springframework/groupIdartifactIdspring-test/artifactIdversion5.3.9/versionscopetest/scope/dependency!--aop--dependencygroupIdorg.aspectj/groupIdartifactIdaspectjweaver/artifactIdversion1.9.6/version/dependencydependencygroupIdjunit/groupIdartifactIdjunit/artifactIdversion4.13/versionscopetest/scope/dependencydependencygroupIdcom.fasterxml.jackson.core/groupIdartifactIdjackson-databind/artifactIdversion2.9.6/version/dependency /dependencies service public interface CRUD {void select();void insert();void update();void delete(); } public class CRUDService implements CRUD {public void select() {System.out.println(假装自己执行了select);}public void insert() {System.out.println(假装自己执行了insert);}public void update() {System.out.println(假装自己执行了update);}public void delete() {System.out.println(假装自己执行了delete);} } aop public class CRUDAdvice {public void before(){System.out.println(前置通知);}public void afterReturning(){System.out.println(后置通知);}public void afterThrowing(){System.out.println(异常通知);}public void after(){System.out.println(最终通知);}public void around(ProceedingJoinPoint ProceedingJoinPoint){System.out.println(环绕开始);try {ProceedingJoinPoint.proceed();} catch (Throwable throwable) {throwable.printStackTrace();}System.out.println(环绕结束);} } applicationContent.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/aophttps://www.springframework.org/schema/aop/spring-aop.xsdbean idcrudService classcn.winkto.service.CRUDService/beanbean idcrudAdvice classcn.winkto.aop.CRUDAdvice/beanaop:configaop:aspect refcrudAdviceaop:before methodbefore pointcutexecution(* cn.winkto.service.CRUDService.*(..))/aop:beforeaop:after methodafterReturning pointcutexecution(* cn.winkto.service.CRUDService.*(..))/aop:after/aop:aspect/aop:config /beans 测试 RunWith(SpringJUnit4ClassRunner.class) ContextConfiguration(value {classpath:applicationContent.xml}) public class MyTest {Autowiredprivate CRUD crud;Testpublic void test(){crud.select();} } 8.3、Aop详解 8.3.1、切点表达式 execution([修饰符] 返回值类型 包名.类名.方法名(参数)) 访问修饰符可以省略返回值类型、包名、类名、方法名可以使用星号 * 代替代表任意包名与类名之间一个点 . 代表当前包下的类两个点 … 表示当前包及其子包下的类参数列表可以使用两个点 … 表示任意个数任意类型的参数列表 8.3.2、切点表达式的抽取 ?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/aophttps://www.springframework.org/schema/aop/spring-aop.xsdbean idcrudService classcn.winkto.service.CRUDService/beanbean idcrudAdvice classcn.winkto.aop.CRUDAdvice/beanaop:configaop:aspect refcrudAdviceaop:pointcut idpoint1 expressionexecution(* cn.winkto.service.CRUDService.*(..))/aop:before methodbefore pointcut-refpoint1/aop:beforeaop:after methodafterReturning pointcut-refpoint1/aop:after/aop:aspect/aop:config /beans ?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/aophttps://www.springframework.org/schema/aop/spring-aop.xsdbean idcrudService classcn.winkto.service.CRUDService/beanbean idcrudAdvice classcn.winkto.aop.CRUDAdvice/beanaop:configaop:pointcut idpoint1 expressionexecution(* cn.winkto.service.CRUDService.*(..))/aop:aspect refcrudAdviceaop:before methodbefore pointcut-refpoint1/aop:beforeaop:after methodafterReturning pointcut-refpoint1/aop:after/aop:aspect/aop:config /beans 8.3.3、通知类型 aop:通知类型 method“通知类中方法名” pointcut“切点表达式/aop:通知类型 名称标签说明前置通知aop:before用于配置前置通知指定增强的方法在切入点方法之前执行后置通知aop:afterReturning用于配置后置通知。指定增强的方法在切入点方法之后执行异常通知aop:afterThrowing用于配置异常通知。指定增强的方法出现异常后执行最终通知aop:after用于配置最终通知。无论切入点方法执行时是否有异常都会执行环绕通知aop:around用于配置环绕通知。开发者可以手动控制增强代码在什么时候执行 后置通知与异常通知互斥环绕通知一般独立使用 9、Spring注解开发AOP部分 导入依赖 dependencies!--spring--dependencygroupIdorg.springframework/groupIdartifactIdspring-context/artifactIdversion5.3.9/version/dependency!--spring-test--dependencygroupIdorg.springframework/groupIdartifactIdspring-test/artifactIdversion5.3.9/versionscopetest/scope/dependency!--aop--dependencygroupIdorg.aspectj/groupIdartifactIdaspectjweaver/artifactIdversion1.9.6/version/dependencydependencygroupIdjunit/groupIdartifactIdjunit/artifactIdversion4.13/versionscopetest/scope/dependencydependencygroupIdcom.fasterxml.jackson.core/groupIdartifactIdjackson-databind/artifactIdversion2.9.6/version/dependency /dependencies service public interface CRUD {void select();void insert();void update();void delete(); } public class CRUDService implements CRUD {public void select() {System.out.println(假装自己执行了select);}public void insert() {System.out.println(假装自己执行了insert);}public void update() {System.out.println(假装自己执行了update);}public void delete() {System.out.println(假装自己执行了delete);} } aop Component //标注为切面类 Aspect public class CRUDAdvice {Pointcut(execution(* cn.winkto.service.CRUDService.*(..)))public void point(){}Before(point())public void before(){System.out.println(前置通知);}AfterReturning(point())public void afterReturning(){System.out.println(后置通知);}public void afterThrowing(){System.out.println(异常通知);}public void after(){System.out.println(最终通知);}public void around(ProceedingJoinPoint ProceedingJoinPoint){System.out.println(环绕开始);try {ProceedingJoinPoint.proceed();} catch (Throwable throwable) {throwable.printStackTrace();}System.out.println(环绕结束);} } config Configuration ComponentScan(cn.winkto) //开启自动aop代理 EnableAspectJAutoProxy public class WinktoConfig {Bean(objectMapper)public ObjectMapper getObjectMapper(){return new ObjectMapper();} } 测试 RunWith(SpringJUnit4ClassRunner.class) ContextConfiguration(classes {WinktoConfig.class}) public class MyTest {Autowiredprivate CRUD crud;Testpublic void test(){crud.select();} } 10、Spring事务 编程式事务直接把事务的代码和业务代码耦合到一起在实际开发中不用下文不进行详细阐述声明式事务采用配置的方式来实现的事务控制业务代码与事务代码实现解耦合 10.1、声明式事务基于XML整合mybatis 实体类 public class Person {private int pid;private String pname;private String ppassword; } mapper public interface PersonMapper {ListPerson selectPerson(); } public class PersonMapperImpl implements PersonMapper {private SqlSession sqlSession;public PersonMapperImpl(SqlSession sqlSession) {this.sqlSession sqlSession;}public ListPerson selectPerson() {return sqlSession.getMapper(PersonMapper.class).selectPerson();} } 映射文件 ?xml version1.0 encodingUTF-8 ? !DOCTYPE mapperPUBLIC -//mybatis.org//DTD Mapper 3.0//ENhttp://mybatis.org/dtd/mybatis-3-mapper.dtd mapper namespacecn.winkto.mapper.PersonMapperselect idselectPerson resultTypePersonselect * from person/select /mapper 数据库配置文件 drivercom.mysql.jdbc.Driver urljdbc:mysql://localhost:3306/test?useUnicodetruecharacterEncodingutf-8useSSLfalseserverTimezone Asia/Shanghai userroot passwordblingbling123. mybatis配置文件 ?xml version1.0 encodingUTF-8 ? !DOCTYPE configurationPUBLIC -//mybatis.org//DTD Config 3.0//ENhttp://mybatis.org/dtd/mybatis-3-config.dtdconfigurationsettingssetting namelogImpl valueSTDOUT_LOGGING//settingstypeAliasespackage namecn.winkto.bean/package/typeAliasesmapperspackage namecn.winkto.mapper//mappers /configuration spring配置文件 ?xml version1.0 encodingUTF-8? beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlns:contexthttp://www.springframework.org/schema/context xmlns:txhttp://www.springframework.org/schema/txxmlns:aophttp://www.springframework.org/schema/aopxsi:schemaLocationhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttps://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd!--开启注解扫描--context:component-scan base-packagecn.winkto /context:property-placeholder locationclasspath:database.properties/bean iddataSource classcom.alibaba.druid.pool.DruidDataSourceproperty namedriverClassName value${driver}/property nameurl value${url}/property nameusername value${user}/property namepassword value${password}//bean!--sqlSessionFactory--bean idsqlSessionFactory classorg.mybatis.spring.SqlSessionFactoryBeanproperty namedataSource refdataSource /property nameconfigLocation valuemybatis-config.xml //bean!--sqlsession--bean idsqlsession classorg.mybatis.spring.SqlSessionTemplateconstructor-arg namesqlSessionFactory refsqlSessionFactory //beanbean idpersonMapper classcn.winkto.mapper.PersonMapperImplconstructor-arg namesqlSession refsqlsession //bean!--事务管理器--bean idtx classorg.springframework.jdbc.datasource.DataSourceTransactionManagerconstructor-arg namedataSource refdataSource //bean!--通知增强--tx:advice idtxAdvice transaction-managertxtx:attributestx:method name*//tx:attributes/tx:advice!--织入事务--aop:configaop:pointcut idpoint expressionexecution(* cn.winkto.mapper.PersonMapperImpl.*(..)) /aop:advisor advice-reftxAdvice pointcut-refpoint //aop:config /beans 测试 RunWith(SpringJUnit4ClassRunner.class) ContextConfiguration(value {classpath:applicationContent.xml}) public class MyTest {Autowiredprivate PersonMapper personMapper;Testpublic void test(){System.out.println(personMapper.selectPerson());} } 10.1.1、 事务参数的配置详解 tx:method nameselectPerson isolationREPEATABLE_READ propagationREQUIRED timeout-1 read-onlyfalse/ name切点方法名称可以使用*做匹配类似于模糊查询isolation:事务的隔离级别propogation事务的传播行为timeout超时时间read-only是否只读 10.2、声明式事务基于注解整合mybatis 实体类 public class Person {private int pid;private String pname;private String ppassword; } 数据库配置文件 drivercom.mysql.jdbc.Driver urljdbc:mysql://localhost:3306/test?useUnicodetruecharacterEncodingutf-8useSSLfalseserverTimezone Asia/Shanghai userroot passwordblingbling123. mapper public interface PersonMapper {ListPerson selectPerson(); } Repository(personMapper) public class PersonMapperImpl implements PersonMapper {Autowiredprivate SqlSessionTemplate sqlSession;public PersonMapperImpl(SqlSessionTemplate sqlSession) {this.sqlSession sqlSession;}//配置事务属性可放置在类上kTransactional(propagation Propagation.REQUIRED,isolation Isolation.DEFAULT,timeout -1,readOnly true)public ListPerson selectPerson() {return sqlSession.getMapper(PersonMapper.class).selectPerson();} } 映射文件 ?xml version1.0 encodingUTF-8 ? !DOCTYPE mapperPUBLIC -//mybatis.org//DTD Mapper 3.0//ENhttp://mybatis.org/dtd/mybatis-3-mapper.dtd mapper namespacecn.winkto.mapper.PersonMapperselect idselectPerson resultTypePersonselect * from person/select /mappermybatis配置文件 ?xml version1.0 encodingUTF-8 ? !DOCTYPE configurationPUBLIC -//mybatis.org//DTD Config 3.0//ENhttp://mybatis.org/dtd/mybatis-3-config.dtdconfigurationsettingssetting namelogImpl valueSTDOUT_LOGGING//settingstypeAliasespackage namecn.winkto.bean/package/typeAliasesmapperspackage namecn.winkto.mapper//mappers /configurationconfig Configuration EnableAspectJAutoProxy EnableTransactionManagement ComponentScan(cn.winkto) PropertySource(classpath:database.properties)public class WinktoConfig {Value(${driver})private String driver;Value(${url})private String url;Value(${user})private String user;Value(${password})private String password;Beanpublic DataSource dataSource(){DruidDataSource druidDataSource new DruidDataSource();druidDataSource.setDriverClassName(driver);druidDataSource.setUrl(url);druidDataSource.setUsername(user);druidDataSource.setPassword(password);return druidDataSource;}Beanpublic SqlSessionFactoryBean sqlSessionFactoryBean(Autowired DataSource dataSource){SqlSessionFactoryBean sqlSessionFactoryBean new SqlSessionFactoryBean();sqlSessionFactoryBean.setDataSource(dataSource);sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(mybatis-config.xml));return sqlSessionFactoryBean;}Bean(sqlSession)public SqlSessionTemplate sqlSessionTemplate(Autowired SqlSessionFactoryBean sqlSessionFactoryBean) throws Exception {return new SqlSessionTemplate(sqlSessionFactoryBean.getObject());}Beanpublic DataSourceTransactionManager dataSourceTransactionManager(){return new DataSourceTransactionManager(dataSource());} }测试 RunWith(SpringJUnit4ClassRunner.class) ContextConfiguration(classes {WinktoConfig.class}) public class MyTest {Autowiredprivate PersonMapper personMapper;Testpublic void test(){System.out.println(personMapper.selectPerson());} }

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/82951.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

哪里可以做宝盈网站网站模板 寻模板

RBAC引入了4个顶级资源对象:Role、ClusterRole:角色,用于指定一组权限;RoleBinding、ClusterRoleBinding:角色绑定,用于将角色(权限)赋予给对象 咱们通过Role可以配置命名空间下资源…

澄迈住房和城乡建设局网站微网站免费注册

目录 1_认识Axios库2_axios发送请求3_axios创建实例4_axios的拦截器5_axios请求封装 1_认识Axios库 功能特点: 在浏览器中发送 XMLHttpRequests 请求在 node.js 中发送 http请求支持 Promise API拦截请求和响应转换请求和响应数据 2_axios发送请求 支持多种请求方式: axios…

泉州建站平台江苏省城乡建设部网站首页

在ASP.Net中对各个WebForm控件引入以前没有的EnableViewState属性。这个属性究竟有什么用。我们知道对于WebForm而言,其代码是在服务器端的,以处理客户端的请求。当用户通过浏览器浏览网页的时候,会对网页进行某些操作,比如打开新…

宁波中科网站建设有限公司如何查看域名以前是做什么网站的

对于一个预算有限的创业者来说,选择合适的办公场地是一个重要的决策。不同的办公场地形式有各自的优缺点,需要根据创业者的具体情况和需求来权衡。 一般来说,有以下几种常见的办公场地形式: - 家庭办公:这是最节省成本…

有没有好的ppt网站做参考的怎样做 云知梦 网站 付费网站

目录 一、ISIS协议基础 1、ISIS概述(认识ISIS) 2、ISIS的应用 4、ISIS的工作过程 5、ISIS路由器的类型 6、ISIS区域 7、ISIS报文 8、ISIS基础配置 9、进程号: 10、NET地址 11、ISIS邻居关系 二、邻居表分析 1、ISIS邻居表字段解析…

凡客网站建站教程网站域名登陆地址查询

目录 概述实践监听spring boot ready事件代码 源码初始化流程调用流程 结束 概述 spring boot 版本为 2.7.17 。 整体看一下spring及spring boot 相关事件。 根据下文所给的源码关键处,打上断点,可以进行快速调试。降低源码阅读难度。 实践 spring…

网站建设在哪里找人今天的热点新闻

2018年上班的第二天,就这样背了一个大锅。我们项目中有一个搜索功能,在这一期的版本中,为了增强优化,去除了过滤空格的请求,这样或许能增加很好的用户体验,恰恰相反,偷鸡不成蚀把米。没想到苹果…

angular网站模板下载中国建设银行总行门户网站

为了满足业务需求,低代码技术平台带着更理想的优势特点,广泛用于各中大型企业中,是助力企业实现提质增效、提升开发效率的有力武器。那么,您知道快速自定义表单开发的优势体现在哪里吗?为了帮助大家了解这些详情&#…

电子商务网站建设的过程手机网站html声明

(꒪ꇴ꒪ ),Hello我是祐言QAQ我的博客主页:C/C语言,Linux基础,ARM开发板,软件配置等领域博主🌍快上🚘,一起学习,让我们成为一个强大的攻城狮!送给自己和读者的一句鸡汤🤔&…

哪方面网站搬瓦工 ss wordpress

0 前言 🔥 优质竞赛项目系列,今天要分享的是 🚩 基于深度学习的植物识别算法研究与实现 🥇学长这里给一个题目综合评分(每项满分5分) 难度系数:4分工作量:4分创新点:4分 🧿 更多…

用php做网站和go做网站汕头个人网站推广建设

前言 前段时间,写了个地址的控件,封装成了一个子组件,在其他页面共用。 原文地址:vue利用级联选择器实现全国省市区乡村五级菜单联动 然后当时出现了个bug,也没有太注意,后来才发现的。就是重置不了地址栏…

网站的风格对比信息表深圳网站建设优化服务

一、线程与进程线程定义进程中执行的一个代码段,来完成不同的任务组成:线程ID,当前指令指针(PC),寄存器集合(存储一部分正在执行线程的处理器状态的值)和堆栈进程定义执行的一段程序,一旦程序被载入到内存中准备执行就…

磁力网站怎么做的网站制作的趋势

题目: 编写一个高效的算法来搜索矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性:每行的元素从左到右升序排列。每列的元素从上到下升序排列。 实现: 1. main方法 public static void main(String[] args) {int[][] matrix {{1…

网站大学报名官网入口免费虚拟主机管理系统

java cpu本文是该系列的第1部分,它将为您提供有关如何进行故障排除和识别Java高CPU问题根本原因的综合指南。 本指南也适用于独立的Java程序,但旨在帮助涉及Java EE企业日常生产支持的个人。 它还将包括最常见的高级CPU问题列表以及高级解决方案。 生产…

建设银行网站查询密码怎么设置长沙招聘网官网

文章目录 1 前言2 项目背景3 任务描述4 环境搭配5 项目实现5.1 准备数据5.2 构建网络5.3 开始训练5.4 模型评估 6 识别效果7 最后 1 前言 🔥 优质竞赛项目系列,今天要分享的是 🚩 深度学习手势识别算法实现 - opencv python 该项目较为新颖…

广东省外贸网站建设wordpress 浮动小人

前言 运算符在C#编程语言中扮演着重要的角色,用于执行各种计算和操作。了解运算符的优先级是编写高效和正确代码的关键。本文将深入探讨C#中38个常用运算符的优先级划分和理解,并提供详细的说明和示例,以帮助读者更好地理解运算符的使用。 目…

网站建设的标语火币网站怎么做空

前言 「作者主页」:雪碧有白泡泡 「个人网站」:雪碧的个人网站 「推荐专栏」: ★java一站式服务 ★ ★ React从入门到精通★ ★前端炫酷代码分享 ★ ★ 从0到英雄,vue成神之路★ ★ uniapp-从构建到提升★ ★ 从0到英雄&#xff…

安康创宇网站制作建设软件制作平台免费

我在阅读 Linux0.11 源码时,对一个指令 LDS 感到困惑。 看了下 intel 指令集手册,能猜到 LDS 的功能,但不确定。 于是决定搭建调试环境,看看 LDS 的功能是否真如自己猜测。 首先 make debug 运行 qemu-Linux0.11,命…

网站顶部布局上饶做网站最好的公司

文章目录 系列文档索引五、ProxyFactory源码分析1、案例2、认识TargetSource(1)何时用到TargetSource(2)Lazy的原理(3)应用TargetSource 3、ProxyFactory选择cglib或jdk动态代理原理4、jdk代理获取代理方法…

顺德网站建设要多少钱seo网站营销公司

一、五大数据类型 String类型、List类型、Set类型、ZSet类型、hash类型。 二、String类型 2.1、内存储存模型 2.2、常用操作命令 三、List类型 3.1、概述 list列表,相当于Java中的list集合。特点:元素有序 且 可以重复。 3.2、内存存储模型 3.3、常用…