在我们想要访问运行时的 tomcat 引擎中有一些信息,所以我们在我们的应用程序上下文中有以下内容(从 this blog post 获得):
<bean id="tomcatEngineProxy" class="org.springframework.jmx.access.MBeanProxyFactoryBean">
<property name="objectName" value="Catalina:type=Engine" />
<property name="proxyInterface" value="org.apache.catalina.Engine" />
<property name="useStrictCasing" value="false" />
</bean>
在 Controller 中,我们像这样 Autowiring 它:
@Autowired
private MBeanProxyFactoryBean tomcatEngineProxy = null;
我们不能像博客文章中那样连接 org.apache.catalina.Engine
,因为在构建时我们无法使用该类。它仅在运行时可用,所有不同的 tomcat 版本在不同的机器上运行。
我们能够使用反射从这个@Autowire 中获取我们需要的信息。现在,我们想将此功能移动到服务中。我将其添加到我们的应用上下文中:
<bean id="myService" class="com.foo.bar.MyServiceImpl">
<constructor-arg ref="tomcatEngineProxy" />
</bean>
类看起来像这样:
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.SpringProxy,org.springframework.aop.framework.Advised] to required type [org.springframework.jmx.access.MBeanProxyFactoryBean]: no matching editors or conversion strategy found
我对代理的工作原理和使用方法一无所知,我不确定如何着手进行这项工作。是否有一些声明可以用于匹配的构造函数 arg? Controller 中有效的 @Autowire 与无效的构造函数参数之间有何不同?
最佳答案
这是因为您的工厂 bean 将结果公开为引擎接口(interface):
<property name="proxyInterface" value="org.apache.catalina.Engine" />
因此,如果您尝试连接“tomcatEngineProxy”bean 本身,它唯一兼容的分配是“org.apache.catalina.Engine”,因为创建的代理仅实现该接口(interface)。
尝试直接引用工厂 bean(注意 & 符号,它是查找创建对象的实际工厂 bean 的语法,而不是对象本身):
<constructor-arg ref="&tomcatEngineProxy" />
关于java - 如何将代理注入(inject)服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12499878/