【问题标题】:Spring - How to know if cglib or jdk dynamic proxy was applied to a beanSpring - 如何知道 cglib 或 jdk 动态代理是否应用于 bean
【发布时间】:2017-05-05 15:00:12
【问题描述】:

我正在准备 Spring Core 证书考试,并且正在对框架进行一些测试。

我想知道是否有办法知道 Bean 是否被 CGLIB 或 JDK 库代理。

我已经知道基本概念,例如如果您使用接口声明 Bean,Spring 将使用 JDK 来代理它(除非您另有说明)。如果你直接在一个类上声明一个 bean,它将使用 CGLIB 通过继承来代理它。

我想知道的是在调试时我应该寻找什么来检查使用了哪个库。

鉴于以下代码,当我调试它时,我看不到创建的 bean 实例有任何差异。我期待在没有接口的 bean 中看到像 ConcreteBean$CGLIB 这样的东西......

编辑:我现在明白只有在 PostProcessor 需要添加功能时才会由 spring 创建代理,但我仍然想知道在调试器中查找什么以查找是否是否应用了 CGLIB。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MainConfig.class)
public class ProxiesTest {

    @Autowired
    RandomBean randomBean;
    @Autowired
    ConcreteBean concreteBean;

    public void setUp() {
    }

    @Test
    public void randomBeanTest() {
        randomBean.doSomething();
    }
    @Test
    public void concreteBeanTest() {
        concreteBean.doSomething();
    }
}

public class ConcreteBean {
    public void doSomething() {
        String concreteBean = "hello";
    }

    @PreDestroy
    public void destroy() {
        System.out.print("ConcreteBean Destroy");
    }
}

public interface RandomBean {

    public void doSomething();

    public void destroy();
}
public class RandomBeanImpl implements RandomBean {

    @Autowired
    ApplicationContext context;

    public void doSomething() {
        context.getParentBeanFactory();
    }

    public void destroy() {
        System.out.print("RandomBean destroyed");
    }
}
@Configuration
@ComponentScan(basePackages = "com.certification.postprocessors")
public class MainConfig {

    @Bean
    public ConcreteBean concreteBean(){
        return new ConcreteBean();
    }

    @Bean
    public RandomBean randomBean() {
        return new RandomBeanImpl();
    }
}

【问题讨论】:

    标签: spring


    【解决方案1】:

    当一个 bean 被 Spring CGLIB 代理包装时,它声明 $$EnhancerBySpringCGLIB。

    JDK 代理显示为 $Proxy

    It looks like this in the debugging console

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-26
      • 1970-01-01
      • 2015-08-09
      • 2011-11-30
      • 1970-01-01
      • 2013-05-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多