tomcat引擎中有一些我们想要访问运行时的信息,所以我们在app环境中有以下内容(从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>
在控制器中,我们就像这样自动装配它:
@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匹配?在工作的控制器中的@Autowire和不起作用的构造函数arg之间有什么不同?
答案 0 :(得分:4)
这是因为您的工厂bean将结果公开为引擎接口:
<property name="proxyInterface" value="org.apache.catalina.Engine" />
因此,如果您尝试连接“tomcatEngineProxy”bean本身,那么只有兼容的分配是“org.apache.catalina.Engine”,因为创建的代理只实现了该接口。
尝试直接引用工厂bean(注意&符号,这是查找创建对象而不是对象本身的实际工厂bean的语法):
<constructor-arg ref="&tomcatEngineProxy" />
答案 1 :(得分:0)
我认为@Autowired
有效,因为绑定是根据Bean的类型(即MBeanProxyFactoryBean
)完成的,但是对构造函数参数的绑定是通过名称和您提供的名称来完成的{ {1}}与您期望的类型不匹配,因为使用FactoryBean创建的bean的类型与FactoryBean的类型不同。
看起来最简单的解决方案是将tomcatEngineProxy
更改为:
MyServiceImpl
这应该可以解决问题。