dnc*_*253 5 java proxy spring dependency-injection
tomcat引擎中有一些我们想要访问运行时的信息,因此我们在应用程序上下文中有以下内容(从此博客文章中获取):
<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>
Run Code Online (Sandbox Code Playgroud)
在控制器中,我们然后像这样自动装配它:
@Autowired
private MBeanProxyFactoryBean tomcatEngineProxy = null;
Run Code Online (Sandbox Code Playgroud)
我们无法org.apache.catalina.Engine
像在博客文章中那样接线,因为在构建时我们无法使用该类.它仅在运行时可用,并且在不同的计算机上运行所有不同的tomcat版本.
我们能够使用反射从这个@Autowire获取我们需要的信息.现在,我们希望将此功能转移到服务中.我将此添加到我们的应用上下文中:
<bean id="myService" class="com.foo.bar.MyServiceImpl">
<constructor-arg ref="tomcatEngineProxy" />
</bean>
Run Code Online (Sandbox Code Playgroud)
这堂课看起来像这样:
public class MyServiceImpl implements MyService
{
public MyServiceImpl(MBeanProxyFactoryBean tomcatEngineProxy) throws Exception
{
//stuff with the proxy
}
.....
}
Run Code Online (Sandbox Code Playgroud)
当我这样做时,我收到以下错误:
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
Run Code Online (Sandbox Code Playgroud)
基本上不知道代理如何工作以及如何使用它们,我不知道如何使这项工作成功.是否有一些声明我可以用于我的构造函数arg匹配?在工作的控制器中的@Autowire和不起作用的构造函数arg之间有什么不同?
这是因为你的工厂 bean 将结果公开为引擎接口:
<property name="proxyInterface" value="org.apache.catalina.Engine" />
Run Code Online (Sandbox Code Playgroud)
因此,如果您尝试连接“tomcatEngineProxy”bean 本身,则唯一兼容的分配是“org.apache.catalina.Engine”,因为创建的代理仅实现该接口。
尝试直接引用工厂 bean(注意&符号,它是查找创建对象而不是对象本身的实际工厂 bean 的语法):
<constructor-arg ref="&tomcatEngineProxy" />
Run Code Online (Sandbox Code Playgroud)