【问题标题】:what is difference implement interface at cglib proxy?cglib 代理的实现接口有什么区别?
【发布时间】:2019-05-20 12:19:57
【问题描述】:

我在 Spring 中使用 ProxyFactory 制作了 2 个代理对象。 一个代理对象使用接口,一个代理对象不使用接口。 但不工作 JDK 动态代理。所有代理对象都使用 cglib。 实现接口调用真实方法的代理对象。 未实现接口的代理对象出现意外结果。 两个 cglib 代理对象有什么区别? 两者的唯一区别就是界面。

// Not implement interface
open class Person: AbstractPerson() {
}

abstract class AbstractPerson(var age: Int? = null,
                              var name: String? = null) {
    fun init() {
        this.age = 31
        this.name = "LichKing"
    }

    fun introduce(): String = "age: $age name: $name"
}
// Implement interface
open class PersonImpl: AbstractPersonImpl() {
}

abstract class AbstractPersonImpl(var age: Int? = null,
                                  var name: String? = null): PersonInterface {
    fun init() {
        this.age = 31
        this.name = "LichKing"
    }

    override fun introduce(): String = "age: $age name: $name"
}

interface PersonInterface {
    fun introduce(): String
}
// Test
class PersonTest {
    @Test
    fun implementInterface() {
        val p = PersonImpl()
        p.init()

        val proxyFactory: ProxyFactory = ProxyFactory()

        proxyFactory.setTarget(p)

        val proxy = proxyFactory.proxy as PersonImpl

        println(proxy.javaClass)
        println(proxy.introduce()) // "age: 31 name: LichKing"
    }

    @Test
    fun notImplementInterface() {
        val p = Person()
        p.init()

        val proxyFactory: ProxyFactory = ProxyFactory()

        proxyFactory.setTarget(p)

        val proxy = proxyFactory.proxy as Person

        println(proxy.javaClass)
        println(proxy.introduce()) // "age: null name: null"
    }
}

【问题讨论】:

    标签: spring-boot kotlin cglib


    【解决方案1】:

    kotlin 方法的默认选项是final。 原因是introduce 方法没有被扩展。 使用接口时默认选项为open,因此可以扩展。

    gradle 插件kotlin-spring 仅用于 spring 注释。 它不适用于抽象类。

    【讨论】:

      猜你喜欢
      • 2012-05-26
      • 1970-01-01
      • 1970-01-01
      • 2012-03-24
      • 1970-01-01
      • 2016-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多