Spring

Spring

官方下载地址:http://repo.spring.io/release/org/springframework/spring

GitHub:https://github.com/spring-projects/spring-framework

提起Spring就不得不提IOC(控制反转)和AOP(面向切面编程)

1、IOC

现在正常我们的项目都会被分层

比如使用:

UserService 服务层接口

UserServiceImpl 服务层实现类

UserDao 数据访问层接口

UserDaoImpl 数据访问层实现类

一般我们的UserServiceImpl中都会有UserDaoImpl的实例

private UserDao userDao = new UserDaoImpl();

这样才能去使用userDao,但是这有一个坏处,当项目很大,创建了很多dao,每个service中也都有dao的实现,当需要把一整个dao换成另一个的时候,就需要修改很多代码。这也就是耦合度过高,那么如何才能避免这样的现象?

下面来看这段代码

private UserDao userDao;
public void setUserDao(UserDao userDao){
    this.userDao = userDao
}

这段代码与上面的区别就是,没有直接给userDao进行赋值,而是采用set的方式让别人进行调用来给userDao赋值。

区别

  • 第一段代码中,userDao的实现是掌握在程序员的手中,也就是程序写成什么样,UserDao就是什么值
  • 第二段代码中,userDao的实现是掌握在用户的手中,用户set一个什么值userDao就是什么值,也就是说当userDao有多个实现类,用什么实现类用户可以自己选择

这也就是IOC的原型,把程序的控制权交给调用者,而不是被调用者自己

控制反转IOC是一种设计思想,DI(依赖注入)是实现IOC的一种方法,也有人认为DI只是IOC的另一种说法,在没有IOC的容器中我们使用面向对象编程,对象的创建和对象之间的关系只存在编码中,控制反转后将对象的创建权交给了第三方

spring中可以使用注解也可以使用配置来实现控制反转

2、HelloSpring

简单的spring代码我就不写了,百度有许多

我想说的是spring的控制反转思想:

当我们在application.xml中创建一个实例比如User

在使用的时候,我们通过xml得到这个User

在这其中我们的User对象是由spring创建,User对象中的值也是由spring容器去配置
这个过程就叫做控制反转:
- 控制:谁来控制创建对象,传统的应用对象的创建是由本身决定,现在是由spring创建
- 反转:程序本身不创建对象,而成为了被动的接受对象
- 依赖注入:使用set方法进行注入,spring配置对象的属性的时候,必须要求实体类有对应的set方法
IOC是一种编程思想由主动编程变成了被动的接收
在spring中我们不用再去程序中修改什么,而是去配置中进行修改
所谓的IOC:就是由spring来创建,管理,装配对象

3、IOC创建对象的方式

在bean.xml文件被加载的时候,容器中的对象就已经被初始化了(直接加载,缺点浪费资源)

并且使用的是单例模式

4、依赖注入

4.1、注入方式

spring中有三种注入方式

1、使用构造器注入

2、使用set注入

  • 依赖:bean对象依赖于容器
  • 注入:bean对象中的所有属性都由容器来注入

3、使用扩展方式注入

4.2、bean的作用域

除了前两个后面的都是关于web的,所以先看前两个

1、singleton(单例模式)

<bean id="student" class="com.zhang.entity.Student" scope="singleton">

​ 每次得到的都是同一个对象,可以用==来验证

2、prototype(原型模式)

<bean id="student" class="com.zhang.entity.Student" scope="prototype">

​ 每次得到的都是不同的对象

5、bean 的自动装配

  • 自动装配是spring满足bean依赖的一种方式

  • 通过上下文自己去寻找bean并进行配置

    在spring中三种装配的方式

    1、在xml中显示的配置

    2、在java中显示的配置

    3、隐式的自动装配【重要】

5.1、搭建测试环境

项目结构图
实体类:

@Data
public class Dog {
    public void show(){
        System.out.println("wang~");
    }
}
@Data
public class People {
    private Dog dog;
}

测试类:

public class MyTest {
    @Test
    public void Test(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
        People people = applicationContext.getBean("people", People.class);
        people.getDog().show();
 
   }
}

按类型自动装配:

<?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">

    <bean id="dog" class="com.zhang.entity.Dog"/>

    <bean id="people" class="com.zhang.entity.People" autowire="byType">

    </bean>

</beans>

按名称自动装配:

<bean id="dog" class="com.zhang.entity.Dog"/>

<bean id="people" class="com.zhang.entity.People" autowire="byName">

</bean>
  • 按类型自动装配:spring会根据people中的属性类型自动去寻找与其类型相同的对装配进入
  • 按名称自动装配:spring会根据people中的属性set后面的名称自动去寻找与其名称相同的对象装配进入

按类型装配可以直接省略dog的ID但是当有两个dog对象存在的时候会报错

按名称自动装配的时候如果dogbean的id与people中set后面的值不同则会报错

6、注解【重点】

在beans.xml中

导入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: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/>  注解的支持


    <bean id="dog" class="com.zhang.entity.Dog"/>
    <bean id="people" class="com.zhang.entity.People"/>


</beans>

@Autowired注解

修改People类:

@Data
public class People {
    @Autowired
    private Dog dog;
}
  • 使用Autowired会现根据type来找,找不到再根据name来找

    先使用type去xml中找,当有多个相同的type对象时,会去比较id如果id有匹配的则装入,如果id没有匹配的就报错,这时可以通过下面的Qualifier注解解决

  • @Autowired(required = false)
    这样使用代表所修饰的属性可以为空,默认是true
    
  • 它也可以通过Qualifier来唯一指定一个name相同的对象装入

    @Autowired
    @Qualifier(value = "dog")
    

@Resource注解

修改People类

@Data
public class People {
    @Resource
    private Dog dog;
}
  • 使用Resource会现根据name来找,找不到再根据type来找,他类似于@Autowired
    @Qualifier(value = “dog”)两个的集合体

​ 先判断name如果name没有相同的就找type如果type有多个就报错如果只有一个则装入,可以使用

@Data
public class People {
    @Resource(name = "dog1")
    private Dog dog;
}

可以这样来指定装入id为dog1的dog对象

7、使用注解开发

7.1、@Component注解

其修饰的类被spring所管理了,可以把他看作是一个bean放在了xml中

  • @Repository   修饰数据访问层
    
  • @Controller   修饰控制层
    
  • @Service      修饰服务层
    

这三个其实和Component作用是一样的只是被用于不同的场合

7.2、@Configuration注解

@Configuration注解的作用是可以把他当作一个配置类和相当于之前beans.xml中的beans标签,可以在其中配置多个bean
它也会被spring所托管因为本身他也是一个@Component

创建bean的两种方式:

  • 项目结构图:
  • 方式一:直接添加注解@Bean
@Configuration
public class MyConfig {
    @Bean
    public User getUser(){
        return new User();
    }

}
public class User {
    @Value("zhangsan")
    private String name;

    public User() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}
@Test
public void MyTest(){
    ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyConfig.class);
    User user = applicationContext.getBean("getUser", User.class);
    System.out.println(user);
}

在这里面getUser()方法被@Bean修饰,就说明其是一个bean,相当于于xml中的

<bean id="getUser" class="com.zhang.entity.User"/>

id是getUser的方法名,class则是getUser()的返回值

所以在后面的测试中需要使用getBean(“getUser”, User.class);不然无法取到值

  • 方式二:

    @Configuration
    @ComponentScan("com.zhang.entity")
    public class MyConfig {
    
    }
    
@Component
public class User {
    @Value("zhangsan")
    private String name;

    public User() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}
@Test
public void MyTest(){
    ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyConfig.class);
    User user = applicationContext.getBean("user", User.class);
    System.out.println(user);
}

@ComponentScan(“com.zhang.entity”)这句话相当于xml中的

<context:component-scan base-package="com.zhang.entity"/>

他读取指定包下的所有注解

当User用@Component修饰后就代表其是一个bean

MyConfig使用@ComponentScan(“com.zhang.entity”)扫描到entity下面的User类是一个bean就会将其管理

所以在Test中我们需要写成getBean(“user”, User.class);使用user来getBean

7.3、@Import注解

当有多个类是使用@Configuration修饰的时候就相当于多个xml文件下的多个Beans标签

创建一个MyConfig2

@Configuration
@ComponentScan("com.zhang.entity")
public class MyConfig2 {

}

在MyConfig类上添加@Import(MyConfig2.class)

@Configuration
@ComponentScan("com.zhang.entity")
@Import(MyConfig2.class)
public class MyConfig {

}

这样就相当于xml中的

<import resource="MyConfig2.xml"/>

import就是将两个配置文件合并到一起,使MyConfig可以使用MyConfig2中的bean

8、AOP

使用AOP就不得不说代理模式

8.1、代理模式

静态代理

代理模式重要的几个角色:

  • 抽象角色,一般是抽象类或者接口
  • 代理角色,代理真实角色并且可以做一些附属操作
  • 真实角色,被代理的角色,与代理角色一样都需要去实现抽象角色
  • 客户,客户端访问代理角色

一个租房场景:我们可以直接找房东租房,也可以找房屋中介租房,但是找房屋中介的好处是你可以看很多房子并且他会给你提供许多合同和别的业务,房东也更愿意把自己的房子给中介出租因为可以少管一些事。

在这里面客户就是我们想要租房的人,代理角色就是房屋中介,真实角色就是房东,抽象角色就是租房这件事,房东和房屋中介都可以租房给别人

代码:

租房接口

public interface Rent {
    public void rent();
}

真实角色

public class LandLord implements Rent{
    @Override
    public void rent() {
        System.out.println("租房子给别人");
    }
}

代理角色

public class Intermediary implements Rent{

    private LandLord landLord;

    @Override
    public void rent() {
        seeHouse();
        landLord.rent();
        contract();
    }

    public LandLord getLandLord() {
        return landLord;
    }

    public void setLandLord(LandLord landLord) {
        this.landLord = landLord;
    }

    //附属操作(看房)
    public void seeHouse(){
        System.out.println("带你去看房");
    }

    public void contract(){
        System.out.println("代理给你签合同");
    }

}

客户

public class Client {
    public static void main(String[] args) {
        LandLord landLord = new LandLord();
        Intermediary intermediary = new Intermediary();
        intermediary.setLandLord(landLord);
        intermediary.rent();
    }
}

代理模式的好处:

  • 真实角色可以专注于业务不用去管公共的业务
  • 代理角色实现公共的业务,实现业务的分工
  • 业务扩展的时候方便管理

静态代理模式的缺点:

  • 一个真实的角色对应一个代理角色,当真实角色很多的时候代码会翻倍,代码量会很庞大

动态代理

为了解决静态代理的缺点,所以需要动态代理

首先动态代理就没有代理角色这个类了,他是根据ProxyInvocationHandler生成的

//动态代理的本质就是使用反射机制实现
//这个类的作用是自动生成代理类
//这个类更像是一个模板,放到什么地方都可以用
public class ProxyInvocationHandler implements InvocationHandler {

    //被代理的接口,注意这里是Object类型的也就是说它可以接受很多中类型的参数
    private Object object;

    public void setObject(Object object){
        this.object = object;
    }
    //生成代理类
    public Object getProxy(){
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),object.getClass().getInterfaces(),this);
    }

    //处理代理实例,并返回结果
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = method.invoke(object,args);
        return result;
    }
}

Client:

public class Client {
    public static void main(String[] args) {
        //得到一个真实角色
        LandLord landLord = new LandLord();
        ProxyInvocationHandler proxyInvocationHandler = new ProxyInvocationHandler();
        //指定被代理的类,注意这个类是实现了一个抽象接口
        proxyInvocationHandler.setObject(landLord);
        //通过proxyInvocationHandler得到一个代理类
        Rent proxy = (Rent) proxyInvocationHandler.getProxy();
        //调用代理类的方法
        proxy.rent();
    }
}

LandLord和Rent类代码和上面一样

下面来解读Client中具体做了什么

  • 得到一个真实角色

  • 得到proxyInvocationHandler类

  • 将proxyInvocationHandler类中的Object设置为真实角色landLord,它将使用这个object来生成代理类

  • 得到这个代理类并将其转化为Rent类型

  • 当调用

    proxy.rent();时会自动调用

    //处理代理实例,并返回结果
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            Object result = method.invoke(object,args);
            return result;
        }
    //proxy就是上面得到的代理类,method则是rent()方法的反射对象,args就是参数
    //method.invoke(object,args);这其中的object就是上面传入的真实角色landLord,这句话就是使用反射来调用landLord对象的rent()方法
    

    他有静态代理的所有优点

    不需要一个真实角色用一个代理类,动态代理代理的是一个接口也就是

    Rent proxy = (Rent) proxyInvocationHandler.getProxy();

    这个Rent接口,当有多个类实现Rent接口的时候我们就可以都用这一个类进行代理,只是setObject的时候传入不同的类(这些类都实现了Rent接口)

    优点:

    • 真实角色可以专注于业务不用去管公共的业务
    • 代理角色实现公共的业务,实现业务的分工
    • 业务扩展的时候方便管理
    • 一次代理一个接口,一般对应一个业务(上面的租房业务)
    • 一个动态代理类可以代理多个类,只要是实现了同一个接口

说一说代理模式到底可以怎么用:

有人说,反正自己真实角色所有功能都可以实现为什么非要弄出个代理角色来帮他做,因为我们需要代理角色完成一些切面上的业务,比如日志,如果说我们想在调用真实角色方法的时候产生一些日志记录信息,那我们需要在所有真实角色方法上一个个加日志,这样代码量太大了,代理的好处就是我可以在调用方法的时候做些别的事情

比如:

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    //我可以在这前后加方法打印日志
    log();		//打印日志
    Object result = method.invoke(object,args);
    log();
    return result;
}

Method method是一个反射对象,它可以取到关于该方法的所有信息,你完全可以用它去做些判断,来选择做什么或者不做什么

这就是代理的作用。

8.2、AOP

在不影响之前的类的情况下实现动态的增强

明白了动态代理的作用就能很好的理解AOP

AOP就是面向切面编程,通过预编译的方式和运行期间的动态代理实现程序功能的统一维护的一种技术,利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率

最常见的一些横切行为如下面这些:

日志记录,跟踪,优化和监控

事务的处理

持久化

性能的优化

资源池,如数据库连接池的管理

系统统一的认证、权限管理等

应用系统的异常捕捉及处理

针对具体行业应用的横切行为

日志记录,跟踪,优化和监控

事务的处理

持久化

性能的优化

资源池,如数据库连接池的管理

系统统一的认证、权限管理等

应用系统的异常捕捉及处理

针对具体行业应用的横切行为

8.3、如何在Spring中使用AOP【重点】

首先需要导入包:

<dependency>
    <groupId>aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.5.4</version>
</dependency>

创建:

image-20200406102616169

UserService:

public interface UserService {
    public void add();
    public void delete();
    public void update();
    public void query();
}

UserServiceImpl:

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("查询了一个用户");
    }
}

beans.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"
       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">

        <bean id="userService" class="com.zhang.service.UserServiceImpl"/>
        <bean id="log" class="com.zhang.log.Log"/>
        <bean id="afterLog" class="com.zhang.log.AfterLog"/>

<!--    方式一:使用原生的api接口-->
    <aop:config>
<!--        切入点 expression是一个表达式表示要执行的位置,在这里表达的就是UserServiceImpl下的所有方法-->
        <aop:pointcut id="pointcut" 
                      expression="execution(* com.zhang.service.UserServiceImpl.*(..))"/>
        <!--        要执行的东西并且在那个切入点执行-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
    </aop:config>

</beans>

Log类

//这是前置日志
public class Log implements MethodBeforeAdvice {
    /**
     *
     * @param method  将要执行的目标方法
     * @param objects 参数
     * @param o     目标对象
     * @throws Throwable
     */
    @Override
    public void before(Method method, Object[] objects, Object o) throws Throwable {
        System.out.println(method.getName()+"将要运行");
    }
}

AfterLog类

public class AfterLog implements AfterReturningAdvice {
    /**
     *
     * @param returnValue  返回值,其他三个和Log一样
     * @param method
     * @param args
     * @param target
     * @throws Throwable
     */
    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("执行了"+method.getName()+"结果为"+returnValue);
    }
}

Test:

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
        //注意动态代理代理的都是一个接口如果这里使用UserServiceImpl会报错
        UserService userService = applicationContext.getBean("userService", UserService.class);
        userService.add();
   }
}

输出结果:

add将要运行
增加了一个用户
执行了add结果为null

方式二:自定义切面类

image-20200406104049082
public class DiyLog {
    public void before(){
        System.out.println("===========方法执行前===========");
    }

    public void after(){
        System.out.println("===========方法执行后===========");
    }
}
<?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">

        <bean id="userService" class="com.zhang.service.UserServiceImpl"/>
        <bean id="log" class="com.zhang.log.Log"/>
        <bean id="afterLog" class="com.zhang.log.AfterLog"/>
        <bean id="diy" class="com.zhang.diy.DiyLog"/>

    <aop:config>
<!--        ref是要引用的类-->
        <aop:aspect ref="diy">
<!--            切入点-->
            <aop:pointcut id="pointcut" 
               expression="execution(* com.zhang.service.UserServiceImpl.*(..))"/>
            <aop:before method="before" pointcut-ref="pointcut"/>
            <aop:after method="after" pointcut-ref="pointcut"/>
        </aop:aspect>
    </aop:config>

</beans>

使用自定义类在调用方法的指定位置上进行调用

        <aop:before method="before" pointcut-ref="pointcut"/>
        <aop:after method="after" pointcut-ref="pointcut"/>

Test方法不变

方式三:使用注解实现

image-20200406113825861

@Aspect
public class Annotation {

    @Before("execution(* com.zhang.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("===========方法执行前===========");
    }

    @After("execution(* com.zhang.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("===========方法执行后===========");
    }
}
<bean id="userService" class="com.zhang.service.UserServiceImpl"/>
        <bean id="log" class="com.zhang.log.Log"/>
        <bean id="afterLog" class="com.zhang.log.AfterLog"/>
        <bean id="diy" class="com.zhang.diy.DiyLog"/>
        <bean id="annotation" class="com.zhang.diy.Annotation"/>
        <!--开启注解的支持-->
        <aop:aspectj-autoproxy/>

Test类不变

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值