java – 如何将代理注入服务?

前端之家收集整理的这篇文章主要介绍了java – 如何将代理注入服务?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

tomcat引擎中有一些我们想要访问运行时的信息,所以我们在app环境中有以下内容(从this blog post开始):

factorybean">
    

在控制器中,我们然后像这样自动装配它:

@Autowired
private MBeanProxyfactorybean tomcatEngineProxy = null;

我们不能像在博客文章中那样连接org.apache.catalina.Engine,因为在构建时我们无法使用该类.它仅在运行时可用,并且在不同的计算机上运行所有不同的tomcat版本.

我们能够使用反射从这个@Autowire获取我们需要的信息.现在,我们希望将此功能转移到服务中.我将此添加到我们的应用上下文中:

这堂课看起来像这样:

public class MyServiceImpl implements MyService
{
    public MyServiceImpl(MBeanProxyfactorybean tomcatEngineProxy) throws Exception
    {
         //stuff with the proxy
    }
    .....
}

当我这样做时,我收到以下错误

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myService' defined in ServletContext resource [/WEB-INF/spring/root-context.xml]: Unsatisfied dependency expressed through constructor argument with index 0 of type [org.springframework.jmx.access.MBeanProxyfactorybean]: Could not convert constructor argument value of type [$Proxy44] to required type [org.springframework.jmx.access.MBeanProxyfactorybean]: Failed to convert value of type '$Proxy44 implementing org.apache.catalina.Engine,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised' to required type 'org.springframework.jmx.access.MBeanProxyfactorybean'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [$Proxy44 implementing org.apache.catalina.Engine,org.springframework.aop.framework.Advised] to required type [org.springframework.jmx.access.MBeanProxyfactorybean]: no matching editors or conversion strategy found

基本上不知道代理如何工作以及如何使用它们,我不知道如何使这项工作成功.是否有一些声明我可以用于我的构造函数arg匹配?在工作的控制器中的@Autowire和不起作用的构造函数arg之间有什么不同?

最佳答案
这是因为您的工厂bean将结果公开为引擎接口:

因此,如果您尝试连接“tomcatEngineProxy”bean本身,那么只有兼容的赋值是“org.apache.catalina.Engine”,因为创建的代理只实现了该接口.

尝试直接引用工厂bean(注意&符号,这是查找创建对象而不是对象本身的实际工厂bean的语法):

How to inject FactoryBean instead of object it produces?

原文链接:https://www.f2er.com/spring/431469.html

猜你在找的Spring相关文章