Spring
1.springIoc容器 xml配置
添加必要的依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>Spring_Test</artifactId>
<groupId>org.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>Spring_AopTest</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
</dependencies>
</project>
ioc创建对象方式
ioc使用无参构造方法去创建对象 默认!!!
ioc也可以使用有参构造去创建对象
1.下标赋值创建对象
2.通过类型创建对象
3.通过参数名设置
<alias> 即别名 相当于数据库中的别名一样,使用了别名还可以使用原来的id进行访问,也可以使用别名进行访问,只能一对一进行去别名
<bean id="hello" class="com.ahui.test.Hello" name = "helloProgram">
id:bean的一个标识
class:类的全路径名称:包+类的路径
name:相当于也是别名比alias更加的适用,可以取多个,而alias只能一对一,分隔符也可以多种(,或者空格或者;)
<import resource="beans.xml">标签:(适用于团队开发,即将所有人的xml合并成一个xml)
resource表示导入别人的xml配置
Ioc即spring的容器(控制反转),它运用xml或注解方式来创建、管理、装配java的实体类
它可以达到不修改原来代码只修改xml或者注解即达到用户想要的实现
bean标签里面id表示bean的名称,class表示类的全路径
property属性表示注入,相当于类中的setter方法进行注入,它里面的name表示类中的属性,value表示对它注入的值,ref表示链接另一个bean(引用spring容器中建好的对象即java实体类)
2.DI注入
1.构造器注入
2.Set方式注入(重点)
set方式注入
<bean id="address" class="cn.ahui.test.Address">
<property name="address" value="重庆"/>
</bean>
<bean id="student" class="cn.ahui.test.Student">
<!--普通注入 -->
<property name="name" value="阿辉"/>
<!--bean注入 -->
<property name="address" ref="address"/>
<!--数组注入 -->
<property name="books">
<array>
<value>语文</value>
<value>数学</value>
<value>英语</value>
</array>
</property>
<!--List注入 -->
<property name="hobbys">
<!--Set和List一样的注入方式-->
<list>
<value>听歌</value>
<value>写代码</value>
<value>看电影</value>
</list>
</property>
<!-- map注入 -->
<property name="card">
<map>
<entry key="银行卡" value="22481214214"/>
<entry key="身份证" value="4723678274"/>
</map>
</property>
<!-- null注入 -->
<property name="wife">
<null/>
</property>
<!-- Properties注入 -->
<property name="info">
<props>
<prop key="学号">201806134111</prop>
<prop key="性别">男</prop>
<prop key="username">root</prop>
<prop key="password">123456</prop>
</props>
</property>
</bean>
运行结果:
Student{name='阿辉', address=Address(address=null), books=null, hobbys=[听歌, 写代码, 看电影], games=null, card={银行卡=22481214214, 身份证=4723678274}, wife='null', info={学号=201806134111, 性别=男}}
3.拓展方式注入
可以使用p或c标签进行注入
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5CBFsC7L-1606139811139)(C:\Users\19175\AppData\Roaming\Typora\typora-user-images\image-20201109231510934.png)]
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="user" class="cn.ahui.test.User" p:name = "阿辉" p:age="20"/>
</beans>
注意点:p命名和c命名空间不能直接使用,必须要进行导入xml约束!!!
配置文件导入xml
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
3.bean的作用域
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qnDs9pql-1606139811141)(C:\Users\19175\AppData\Roaming\Typora\typora-user-images\image-20201111194458764.png)]
1.单例模式(spring默认机制)
<bean id="user" class="cn.ahui.test.User" p:name = "夏中辉" p:age="20" scope="singleton"/>
2.原型模式:每次从容器中(获取bean)get的时候,都会产生一个新对象
<bean id="user" class="cn.ahui.test.User" p:name = "夏中辉" p:age="20" scope="prototype"/>
3.web作用域
request、session、application只能在web开发中使用
4.spring中bean的自动装配
1.自动装配是spring满足bean依赖的一种方式
2.Spring会在上下文(xml)中自动寻找,并自动给bean装配属性
4.1 Spring的三种装配方式
1.在xml中显示的配置
2.在java中显示配置
3.隐式的自动装配的bean(重点)
4.2 ByName自动装配
byName它会自动在spring容器的上下文中查找与自己对象set方法后面的值对应的bean的id!
<bean id="dog" class="cn.ahui.test.Dog"/>
<bean id="cat" class="cn.ahui.test.Cat"/>
<bean id="people" class="cn.ahui.test.People" scope="singleton" autowire="byName">
<property name="name" value="阿辉"/>
<!-- <property name="dog" ref="dog"/>-->
<!-- <property name="cat" ref="cat"/>-->
</bean>
错误代码:
<bean id="dog" class="cn.ahui.test.Dog"/>
<bean id="cat22" class="cn.ahui.test.Cat"/>
<bean id="people" class="cn.ahui.test.People" scope="singleton" autowire="byName">
<property name="name" value="阿辉"/>
<!-- <property name="dog" ref="dog"/>-->
<!-- <property name="cat" ref="cat"/>-->
</bean>
<!--因为差找不到cat22这个name的值,所以报错 -->
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yfS5C7DD-1606139811143)(C:\Users\19175\AppData\Roaming\Typora\typora-user-images\image-20201111213655956.png)]
4.3 byType自动装配
byType:需要自动装配的类型(即bean的class)必须保持全局唯一的,而byName则相反,只需保持bean的id与类中的属性set的方法后面的名称一致即可
<bean id="dog11" class="cn.ahui.test.Dog"/>
<bean id="cat22" class="cn.ahui.test.Cat"/>
<bean id="people" class="cn.ahui.test.People" scope="singleton" autowire="byType">
<property name="name" value="阿辉"/>
<!-- <property name="dog" ref="dog"/>-->
<!-- <property name="cat" ref="cat"/>-->
</bean>
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5yFuLJ5K-1606139811145)(C:\Users\19175\AppData\Roaming\Typora\typora-user-images\image-20201111214200837.png)]
byType错误示范:不能装配两个相同类型的bean,必须保持唯一,否者报错。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RWsnyeeo-1606139811146)(C:\Users\19175\AppData\Roaming\Typora\typora-user-images\image-20201111214320566.png)]
4.4 使用注解实现自动装配
1.导入约束
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
//注解约束
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
//aop约束
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
</beans>
2.配置注解的支持
<context:annotation-config/>
@Autowired
直接在类属性中使用或者在方法上
使用Autowired之后可以不用写set方法,前提是这个自动装配的属性在IOC(Spring)容器中存在,且符合名字byName
@Nullable 这个字段标记了这个注解,它可以为null,且不报错(因为有些地方当为null时,会报空指针异常,可以用其解决)
等价于
//等价于@Nullable
@Autowired(required = false)
Dog dog;
@Autowired
Cat cat;
private String name;
@Autowired和@Qualifier(value = “xxxx”) 联合使用可以解决自动装配较复杂时,用Qualifier(value = “xxxx”) 指定一个唯一的bean对象的id进行装配
@Resource为java的注解,它可以兼容byName和byType,它会先通过名称查找,如果没找到再通过类型查找(但是它如果存在id不同而类型相同的话,就无法识别)。
@Autowired与@Resource的区别之处:
1.都是属于自动装配,都可以放在属性上
2.@Autowired通过byName方式实现(spring的注解)
3.@Resource它可以兼容byName和byType,它会先通过名称查找,如果没找到再通过类型查找(java注解)
4.执行顺序不同:
4.5注解扫描机制(@Component)
@Component 放在类上,说明这个类在spring中进行管理
//使用context:component-scan 指定扫描哪个包下的bean
<context:component-scan base-package="cn.ahui.test"/>
<context:annotation-config/>
import org.springframework.stereotype.Component;\
//相当于在XML中配置了一个bean(<bean id = user class = "cn.ahui.test.User"/>) ==> @Component
@Component
public class User {
public String name = "阿辉呀";
}
如果没有了赋值public String name;,还可以使用@value实现注入
<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"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 开启注解的支持 -->
<!-- 开启扫描包路径 -->
<context:component-scan base-package="cn.ahui.test"/>
<context:annotation-config/>
</beans>
@Component
public class User {
@Value("阿辉!")
public String name;
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-DcSUx23N-1606139811148)(C:\Users\19175\AppData\Roaming\Typora\typora-user-images\image-20201115134156810.png)]
4.6 衍生注解
在@Component注解中有衍生注解去实现MVC的三层架构
dao层:@Repository
service层:@Service
controller层:@Controller
当使用上衍生注解后,把扫描包改成这四个包的上一层的包即可扫描到全部的类(即出现spring叶子标识)
当这几个类使用上了上面的注解,就表示这些类将被Spring的容器托管
4.7 使用JavaConfig替代xml方式实现注解功能
config类的实现:
package cn.ahui.config;
import cn.ahui.Test.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
//表示这是一个配置类,和之前写的beans.xml一样,它也会被Spring容器进行托管,管理
@Configuration
public class UserConfig {
@Bean //相当于在以前xml中写的bean一样
public User getUser(){
return new User();
}
}
User类:
package cn.ahui.Test;
import lombok.Data;//相当于自动加入了set/get方法
import org.springframework.beans.factory.annotation.Value;
@Data
public class User {
@Value("阿辉ya!!!")//实现值的注入
private String name;
@Value("20") //实现值的注入
private int age;
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
test类的实现
import cn.ahui.Test.User;
import cn.ahui.config.UserConfig;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MyConfigTest {
@Test
public void test(){
//使用配置类方式去实现注解的开发AnnotationConfigApplicationContext(UserConfig.class)
ApplicationContext context = new AnnotationConfigApplicationContext(UserConfig.class);
User getUser = (User) context.getBean("getUser");//getUser就是config里面的方法名(返回User类型的方法名)
System.out.println(getUser.getName());
System.out.println(getUser.getAge());
}
}
5、代理模式
5.1、代理模式(降低耦合)
5.1.1、静态代理
代理模式即中介代理别人出租房子或者其他业务,直接拥有代理权,或者工厂招人,中介就可以通过招到人送到工厂赚取中介费
实现代理模式步骤(静态代理)
1.创建接口
2.真实角色
3.代理角色
4.客户端访问代理角色(以访问代理角色达到访问真实角色的效果)
5.1.2、动态代理(反射实现)
1.动态代理的代理类是动态生成
2.动态代理分为两大类:
基于接口的动态代理 :原生的基于JDK的动态代理
基于类的动态代理:cglib
基于字节码的实现:javasist
Proxy:代理 , InvocationHandler
6、AOP(面向切面编程)(和动态代理有些类似)
6.1.使用原生Spring API实现AOP
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"
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">
<!-- 注册bean -->
<bean id="UserService" class="cn.ahui.Service.UserServiceImpl"/>
<bean id="log" class="cn.ahui.Log.Log"/>
<bean id="AfterLog" class="cn.ahui.Log.AfterLog"/>
<!-- 使用原生的Spring API接口实现AOP -->
<!-- 配置AOP并导入AOP约束 -->
<aop:config>
<!--切入点 -->
<!--pointcut:切入点 expression = "execution(切入到具体类下的某些方法)" (:书写表达式,)
execution(修饰符 返回值 包名.类名/接口名.方法名(参数列表))-->
<aop:pointcut id="pointcut" expression="execution(* cn.ahui.Service.UserServiceImpl.*(..))"/>
<!--执行环绕增加 -->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
</aop:config>
</beans>
接口类
package cn.ahui.Service;
public interface UserService {
public void add();
public void delete();
public void update();
public void query();
}
实现类
package cn.ahui.Service;
public class UserServiceImpl implements UserService{
@Override
public void add() {
System.out.println("增加了一个用户");
}
@Override
public void delete() {
System.out.println("删除了一个用户");
}
@Override
public void update() {
System.out.println("更新了一个用户");
}
@Override
public void query() {
System.out.println("查询了一个用户");
}
}
增添业务日志功能
package cn.ahui.Log;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
//日志类
public class Log implements MethodBeforeAdvice {
//method: 要执行的目标对象的方法
//objects:代表传入参数
//o:表示目标对象
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println(o.getClass().getName()+"类的"+method.getName()+"执行了!!");
}
}
AfterReturningAdvice类的实现
package cn.ahui.Log;
import org.springframework.aop.AfterAdvice;
import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;
public class AfterLog implements AfterReturningAdvice {
//returnValue:需要返回的值
//method:目标对象的方法
//args:需要传入的参数
//target:表示目标对象
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"类,执行了"+method.getName()+"方法,返回结果为:"+returnValue);
}
}
6.2 AOP实现方式二(自定义实现)
ApplicationContext.xml配置:
<!-- 注册bean -->
<bean id="UserService" class="cn.ahui.Service.UserServiceImpl"/>
<bean id="log" class="cn.ahui.Log.Log"/>
<bean id="AfterLog" class="cn.ahui.Log.AfterLog"/>
<!-- 使用原生的Spring API接口实现AOP -->
<!-- 配置AOP并导入AOP约束 -->
<!-- <aop:config>-->
<!-- <!–切入点 –>-->
<!-- <!–pointcut:切入点 expression = "execution(切入到具体类下的某些方法)" (:书写表达式,)–>-->
<!-- <aop:pointcut id="pointcut" expression="execution(* cn.ahui.Service.UserServiceImpl.*(..))"/>-->
<!-- <!–执行环绕增加 –>-->
<!-- <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>-->
<!-- </aop:config>-->
<bean id="diy" class="cn.ahui.diy.DiyPointCut"/>
<aop:config>
<!-- 自定义切面,ref 要引入的类id -->
<aop:aspect ref="diy">
<!--切入点 execution通知在哪儿执行这个方法-->
<aop:pointcut id="point" expression="execution(* cn.ahui.Service.UserServiceImpl.*(..))"/>
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
接口:
package cn.ahui.Service;
public interface UserService {
public void add();
public void delete();
public void update();
public void query();
}
接口实现类:
package cn.ahui.Service;
public class UserServiceImpl implements UserService{
@Override
public void add() {
System.out.println("增加了一个用户");
}
@Override
public void delete() {
System.out.println("删除了一个用户");
}
@Override
public void update() {
System.out.println("更新了一个用户");
}
@Override
public void query() {
System.out.println("查询了一个用户");
}
}
diy类:
package cn.ahui.diy;
public class DiyPointCut {
public void before(){
System.out.println("this is before method!!!");
}
public void after(){
System.out.println("this is after method!!");
}
}
测试类:
import cn.ahui.Service.UserService;
import cn.ahui.Service.UserServiceImpl;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
//动态代理:代理的是接口而不是实现类,如果写实现类就无意义
UserService userService = (UserService) context.getBean("UserService");
userService.add();
userService.delete();
}
}
6.3、使用注解方式实现AOP(简易实现,但功能不如config配置)
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"
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">
<!-- 注册bean -->
<bean id="UserServiceImpl" class="cn.ahui.Service.UserServiceImpl"/>
<bean id="log" class="cn.ahui.Log.Log"/>
<bean id="AfterLog" class="cn.ahui.Log.AfterLog"/>
<bean id="anootationclass" class="cn.ahui.diy.AnnotationClass"/>
<aop:aspectj-autoproxy/>
</beans>
接口:
package cn.ahui.Service;
public interface UserService {
public void add();
public void delete();
public void update();
public void query();
}
接口实现类:
package cn.ahui.Service;
public class UserServiceImpl implements UserService{
@Override
public void add() {
System.out.println("增加了一个用户");
}
@Override
public void delete() {
System.out.println("删除了一个用户");
}
@Override
public void update() {
System.out.println("更新了一个用户");
}
@Override
public void query() {
System.out.println("查询了一个用户");
}
}
注解执行类:
package cn.ahui.diy;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
//使用注解实现AOP
@Aspect
public class AnnotationClass {
@Before("execution(* cn.ahui.Service.UserServiceImpl.*(..))")
public void before(){
System.out.println("方法执行前~~");
}
@After("execution(* cn.ahui.Service.UserServiceImpl.*(..))")
public void After(){
System.out.println("方法执行后");
}
}
实现类
import cn.ahui.Service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
//动态代理:代理的是接口而不是实现类,如果写实现类就无意义
UserService userService = (UserService) context.getBean("UserServiceImpl");
userService.add();
userService.delete();
}
}
Class {
@Before(“execution(* cn.ahui.Service.UserServiceImpl.(…))")
public void before(){
System.out.println(“方法执行前~~”);
}
@After("execution( cn.ahui.Service.UserServiceImpl.*(…))”)
public void After(){
System.out.println(“方法执行后”);
}
}
实现类
```java
import cn.ahui.Service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
//动态代理:代理的是接口而不是实现类,如果写实现类就无意义
UserService userService = (UserService) context.getBean("UserServiceImpl");
userService.add();
userService.delete();
}
}