spring:春天------->给软件行业带来了春天
spring是一个开源的免费的框架(容器)
控制反转(IOC),面向切面编程(AOP)
支持事务的处理,对框架整合的支持!
总结:Spring就是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的框架
在Spring的官网有这个介绍:现代化的Java开发!说白了就是基于Spring的开发!
Spring Boot
一个快速开发的脚手架
基于Spring Boot可以快速开发单个微服务
约定大于配置
Spring Cloud
Spring Cloud是基于Spring Boot实现的
弊端:发展了太久之后,违背了当初的理念,配置十分繁琐 人称"配置地狱!"
https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html
UserDao 接口
UserDaoImpl 接口实现类
UserService 业务接口
UserServiceImpl 业务实现类
在我们之前的业务中,用户的需求可能会影响我们原来的代码,我们需要根据用户的需求去修改源代码。如果程序代码量很大,修改一次代价十分昂贵!
我们使用set实现 已经发生革命性的变化
private UserDao userDao ;
?
//利用set实现动态值得注入
public void setUserDao(UserDao userDao) {
?
this.userDao = userDao;
}
之前,程序是主动创建对象,控制权在程序员手上。
使用了Set注入后,程序不在具有主动性,而是变成了被动接受的对象
这种思想从本质上解决了程序员的问题,程序员不用再去管理对象的创建了,系统的耦合性大大降低,可以更加专注在业务的实现上 这是IOC的原型
控制反转loC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现loC的一种方法,也有人认为DI只是 IoC的另一种说法。没有IoC的程序中,我们使用面向对象编程, 对象的创建与对象间的依赖关系完全硬编码在程序 中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖 对象的方式反转了。
采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一-体, Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。
控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反 转的是loC容器,其实现方法是依赖注入(Dependency Injection,DI)。
private String str;
?
public String getStr() {
return str;
}
?
public void setStr(String str) {
this.str = str;
}
?
<bean id="hello" class="com.xsw.pojo.Hello">
<property name="str" value="Spring"/>
</bean>
public static void main(String[] args) {
//获取Spring的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//我们的对象都在Spring中管理了,我们要使用,直接取出来就可以了
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello.toString());
}
思考问题?
●Hello 对象是谁创建的? hello对象是由Spring创建的
●Hello 对象的属性是怎么设置的? hello对象的属性是由Spring容器设置的,
这个过程就叫控制反转:
控制:谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用Spring后,对象是由Spring来创 建的. 反转:程序本身不创建对象,而变成被动的接收对象.
依赖注入:就是利用set方法来进行注入的. I0C是一种编程思想,由主动的编程变成被动的接收. 可以通过newClassPathXmlApplicationContext去浏览一下底层源码 .
OK,到了现在,我们彻底不用再程序中去改动了,要实现不同的操作,只需要在xmI配置文件中进行修改,所谓的 loC,-句话搞定:对象由Spring来创建,管理,装配!
1 <!--第一种,下标赋值! -->
2 <bean id="user" class="com. kuang. pojo.User">
3
<constructor-arg index="0" value=" 狂神说Java"/>
4 </bean>
1| <!--第:二种方式:通过类型创建,不建议使用! -->
2 <bean id="user" class="com. kuang. pojo.User">
3
<constructor-arg type="java. lang. String" value="qinjiang"/>
4 </bean>
1 <!--第三种,直接通过参数名来设置-->
2 i <bean id="user" class="com. kuang. pojo. User‘">
3
<constructor-arg name="name" value=" 秦疆"/>
4 </bean>
<!--别名,如果添加了别名,我们也可以使用别名获取到这个对象-->
<alias name="user" alias="userNew"/>
<!--
id : bean 的唯一 标识符,也就是相当于我们学的对象名
class : bean 对象所对应的全限定名:包名+类型
name :也是别名,而且name可以同时取多个别名
-->
<bean id="userT" class="com. kuang. pojo.UserT" name="user2 u2,u3;u4">
<property name="name" value="西部开源"/>
</bean>
这个import,一般用于团队开发使用, 它可以将多个配置文件,导入合并为一个
假设,现在项目中有个人开发,这三个人负责不同的的类开发,不同的类需要注册在不同的bean中,我们可以利用import将所有人的beans.xml合并到一起
张三
李四
王五
applicationContext.xml
<import resource="beans.xml"/>
<import resource="beans2.xml"/>
<import resource="beans3.xml"/>
使用的时候直接用总的配置就可以了
前面已经说过了
依赖注入:Set!
依赖:bean对象的创建依赖对象
依赖:bean对象的所有属性,由容器注入
环境搭建
1、复杂类型
private String address;
?
public String getAddress() {
return address;
}
?
public void setAddress(String address) {
this.address = address;
}
真实测试对象
private String name;
private Address address;
private String[] books;
private List<String> hobbys;
private Map<String, String> card;
private Set<String> games;
private String wife;
private Properties info;
beans.xml
测试类
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student) context.getBean("student");
System.out.println(student.getName());
完善beans.xml [官方文档]
我们可以使用 P 或者 C 的方式注入
注意: p 和c 命名 不能直接使用需要导入xml约束
单例模式 【Spring默认默认机制】
<bean id="address" class="com.xsw.pojo.Address" scope="singleton"/>
原型模式
每次从容器中get的时候都会产生新对象
<bean id="address" class="com.xsw.pojo.Address" scope="prototype"/>
其余的 request、session、application、这些个只能再web开发的时候用到!
自动装配是Spring满足bean依赖的一种方式!
Spring会在上下文中自动寻找,并自动给bean装配属性
在Spring中有三种装配方式
在xml中显示的配置
在Java中显示的配置
隐式的自动装配bean [重要的]
环境搭建:一个人有两个宠物!
<!-- byName: 会自动在容器上下文中查找,和自己对象set方法后面的值对应的 beanid --> <bean id="people" class="com.xsw.pojo.People" autowire="byName"> <property name="name" value="XSW"/> </bean>
<bean id="cat" class="com.xsw.pojo.Cat"/> <bean id="dog" class="com.xsw.pojo.Dog"/> <!-- byType: 会自动在容器上下文中查找,和自己对象属性类型相同的 bean! 弊端:必须保持属性唯一 --> <bean id="people" class="com.xsw.pojo.People" autowire="byType"> <property name="name" value="XSW"/> </bean>
小结:
byname的时候,需要保证所有bean的id唯一, 并且这个bean需要和自动注入的属性的set方法的值一致!
bytype的时候,需要保证所有bean的class唯一 , 并且这个bean需要和自动注入的属性的类型一致!
要使用注解须知:
导入约束:context
配置注解的支持 : context:annotation-config/ [重要!]
<?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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <context:annotation-config/> </beans>
@Autowired
直接在属性上使用即可!也可以在set方式上使用!
使用Autowired我们可以不用编写Set方法了,前提是你这个自动装配的属性在I0C (Spring) 容器中存在,且符合名字byname!
科普:
@Nullable 字段标记了这个注解,说明这个字段可以为空!
public @interface Autowired { boolean required() default true; }
测试代码
public class People { @Autowired private Dog dog; //如果显示定义了Autowired 的 required 为 false 说明这个对象可以为null 否则不允许为空 @Autowired(required = false) private Cat cat; private String name; }
如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解[@Autowired] 完成的时候、我们可以使用@Qualifier(value="xxx" )去配置@Autowired的使用,指定一个唯一 的bean对象注入!
public class People { @Autowired @Qualifier(value = "某个值") private Dog dog; @Autowired(required = false) private Cat cat; private String name; }
@Resource注解
pub1ic class Peop1e { @Resource(name = "cat2") private Cat cat; @Resource private Dog dog; }
小结:
@Resource和@ Autowired的区别:
都是用来自动装配的,都可以放在属性字段上
@ Autowired通过byType的方式实现,而且必须要求这个对象存在! [常用]
@ Resource默认通过byname的方式实现,如果找不到名字,则通过byType实现! 如果两个都找不到的情况 下,就报错! [常用]
执行顺序不同: @ Autowired通过byType的方式实现,@ Resource默认通过byname的方式实现
使用注解开发必须保证导入 aop的包
使用注解开发必须导入context的约束 ,增加注解的支持
<?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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"> <context:component-scan base-package="com.xsw.pojo"/> <context:annotation-config/> </beans>
bean
属性如何注入
package com.xsw.pojo; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component // 等价于<bean id="user" class="com.xsw.pojo.User"/> Component :组件 public class User { @Value("辛思伟") //Value 等价于 <property name="name" value="辛思伟"></property> public String name; //在set 方法上面也可以 public void setName(String name) { this.name = name; } }
衍生的注解
@Component 有几个衍生注解,我们在web开发中,会使用mvc分层架构
dao [@Repository]
service [@Service]
controller [@Controller]
这四个注解功能是一样的,都是代表将某个类注册到Spring容器中,装配bean!
自动装配置
@Autowired : 自动装配通过类型。名字 如果Autowired不能唯一自 动装配上属性,则需要通过@Qualifier(value= "xxx") @Nul1able 字段标记了这个注解,说明这个字段可以为nul1; @Resource: 自动装配通过名字。类型。
作用域
package com.xsw.pojo; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component // 等价于<bean id="user" class="com.xsw.pojo.User"/> Component :组件 //单例模式 @Scope("singleton") //原型模式 //@Scope("prototype") public class User { @Value("辛思伟") //Value 等价于 <property name="name" value="辛思伟"></property> public String name; //在set 方法上面也可以 public void setName(String name) { this.name = name; } }
小结
xml与注解:
xml更加万能,适用于任何场合!维护简单方便
注解不是自己类使用不了,维护相对复杂!
xmlxml与注解最佳实践:
xml用来管理bean!
注解只负责完成属性的注入!
我们在使用的过程中,只需要注意一个问题:必须让注解生效,就需要开启注解的支持!
<!-- 指定要扫描的包、这个包下的注解就会生效--> <context:component-scan base-package="com.xsw.pojo"/> <context:annotation-config/>
实体类
//这里这个注解的意思。就是说明这个类被Spring接管了。 注册到了容器中 @Component public class user { private string name; public string getNaneO(){ return name; } @value("QINJIANG") //属性注入值 public void setname(string name) ( this.name=name; @Override public string tostring{ return "user{" + "name-"" + name + "\"”+ ‘}; }
配置类
//这个也会Spring容器托管,注册到容器中,因为他本来就是一个@Component // @Configuration代表这是- -个配置类,就和我们之前看的beans. xm1 @Confi guration @ComponentScan("com. kuang. pojo") @Import(KuangConfig2.class) pubTic c1ass KuangConfig { //注册一个bean, 就相当于我们之前写的一个bean标签 //这个方法的名字,就相当于bean标签中的id属性 //这个方法的返回值,就相当于bean标签中的class属性 @Bean pub1ic User user(){ return new user(; //就是返 回要注入到bean的对象! }
测试类
//如果完全使用了配置类方式去做,我们就只能通过AnnotationConfig 上下文来 获取容器,通过配置 类的class对象加载! Applicati onContext context = new Annotati onConfi gApplicati onContext (KuangConfig.class); User getuser = (user) context. getBean("user"); System. out. print1n(getuser . getName()); }
这种纯Java的配置方式,在SpringBoot中随处可见
为什么要学习代理模式,因为代理模式是SpringAOP的底层!
角色分析:
抽象角色: 一般会使用接口或者抽象类来解决
真实角色:被代理的角色
代理角色:代理真实角色,代理真实角色后,我们一般会做一些附属操作
客户:访问代理对象的人!
代码步骤
接口
真实角色
代理角色
客户端访问代理角色
代理模式的好处
可以是真实角色的操作更加纯粹,不用去关注一下公共事务
公共业务就交给代理,实现了业务的分工
公共业务发生扩展时,方便集中管理!
缺点
一个真实角色就会产生一个代理角色,代码量翻倍!开发效率会变低!
AOP:
动态代理和静态代理的角色一样
动态代理的代理类是自动生成的,不是我们直接写好的
动态代理分为两大类:基于接口的动态代理 基于类的动态代理
基于接口-----JDK 动态代理 【在这里我们使用JDK原生代码】
基于类 ----cglib
java字节码实现 :Javasist
需要了解两个类 Proxy : 代理 InvocationHandler :调用处理程序
动态代理的好处:
可以使真实角色的操作更加纯粹!不用去关注一 些公共的业务
公共也就就交给代理角色!实现了业务的分工!
公共业务发生扩展的时候,方便集中管理!
一个动态代理类代理的是一个接口,- -般就是对应的一 类业务
一个动态代理类可以代理多个类,只要是实现了同一个接口即可!|
万能类
package xom.xsw.demo2; import org.junit.experimental.categories.Categories; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; 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 { log(method.getName()); Object invoke = method.invoke(target, args); return invoke; } public void log(String msg){ System.out.println("使用了"+msg+"方法"); } }
Client
package xom.xsw.demo2; import xom.xsw.demo1.UserService; import xom.xsw.demo1.UserServiceImpl; public class Client { public static void main(String[] args) { UserServiceImpl userServiceImpl=new UserServiceImpl(); ProxyInvocationHandler pih = new ProxyInvocationHandler(); pih.setTarget(userServiceImpl); UserService proxy = (UserService) pih.getProxy(); proxy.delete(); } }
AOP (Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能. 的统一维护的一种技术。AOP是0OP的延续,是软件开发中的- -个热点,也是Spring框架中的一-个重要内容,是 函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合 度降低,提高程序的可重用性,同时提高了开发的效率。
提供声明式事务,允许用户自定义切面
横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部 分,就是横切关注点。如日志,安全,缓存,事务等等...
切面(ASPECT) :横切关注点被模块化的特殊对象。即,它是一个类。
通知(Advice) :切面必须要完成的工作。即,它是类中的一一个方法。
目标(Target) :被通知对象。
代理(Proxy) :向目标对象应用通知之后创建的对象。
切入点(PointCut) :切面通知执行的“地点”的定义。
连接点(JointPoint) :与切入点匹配的执行点。
【重点】使用aop织入 需导入依赖包
<dependencies> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.4</version> </dependency> </dependencies>
接口
package com.xsw.Service; public interface UserService { public void add(); public void delete(); public void updata(); public void select(); }
接口实现类
package com.xsw.Service; public class UserServiceImpl implements UserService { public void add() { System.out.println("增加了一个数据"); } public void delete() { System.out.println("删除了一个数据"); } public void updata() { System.out.println("修改了一个数据"); } public void select() { System.out.println("查询了一个数据"); } }
日志
LOG
package com.xsw.log; import org.springframework.aop.MethodBeforeAdvice; import java.lang.reflect.Method; public class LOG implements MethodBeforeAdvice { public void before(Method method, Object[] args, Object target) throws Throwable { System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了"); } }
AfterLog
package com.xsw.log; import org.springframework.aop.AfterReturningAdvice; import java.lang.reflect.Method; public class AfterLog implements AfterReturningAdvice { public void afterReturning(Object o, Method method, Object[] arge, Object target) throws Throwable { System.out.println("执行了"+method.getName()+"的方法 ; 返回值为 :"+o); } }
<?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.xsw.Service.UserServiceImpl"/> <bean id="log" class="com.xsw.log.LOG"/> <bean id="afterLog" class="com.xsw.log.AfterLog"/> <!-- 配置aop 导入依赖--> <aop:config> <!-- 切入点 expression 表达式 :execution (要执行的位置!) --> <aop:pointcut id="pointcut" expression="execution(* com.xsw.Service.UserServiceImpl.*(..))"/> <!-- 执行环绕--> <aop:advisor advice-ref="log" pointcut-ref="pointcut"/> <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/> </aop:config> </beans>
自定义DiyPointcut类
package com.xsw.Diy; public class DiyPointcut { public void after(){ System.out.println("==================方法之后的=============="); } public void before(){ System.out.println("=============方法之前的============"); } }
配置注解
<bean id="diy" class="com.xsw.Diy.DiyPointcut"/> <aop:config> <!-- 自定义切面 ref要引入的类--> <aop:aspect ref="diy"> <!-- 切入点--> <aop:pointcut id="point" expression="execution(* com.xsw.Service.UserServiceImpl.*(..))"/> <!-- 通知--> <aop:before method="before" pointcut-ref="point"/> <aop:after method="after" pointcut-ref="point"/> </aop:aspect> </aop:config>
测试!
创建类
package com.xsw.Diy; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; @Aspect //标注这个类是一个切面 public class AnnotationPoincut { @Before("execution(* com.xsw.Service.UserServiceImpl.*(..))") public void before(){ System.out.println("============方法之前==========="); } }
配置文件
<bean id="annotationPoincut" class="com.xsw.Diy.AnnotationPoincut"/> <!-- Jdk (默认) =proxy-target-class="false" cglib =proxy-target-class="true"--> <aop:aspectj-autoproxy/>
步骤:
导入相关jar包
junit
mybatis
mysq|数据库
spring相关的
aop织入
mybatis-spring [new]
编写配置文件
测试
编写实体类
编写核心配置文件
编写接口
编写Mapper.xml
测试
原文:https://www.cnblogs.com/-xsw000/p/12818998.html