Spring MVC没有找到默认构造函数?

Ror*_*ory 12 java spring web.xml spring-mvc

我遇到了我的Spring控制器问题 - 我没有找到默认的构造函数 - 但是他们确实有一个我试图通过applicationContext.xml创建的构造函数 - 以下是相关的一点:

<bean id="PcrfSimulator" class="com.rory.services.pcrf.simulator.PcrfSimulator" init-method="start">  
</bean>

<bean id="CacheHandler" class="com.rory.services.pcrf.simulator.handlers.CacheHandler">
    <constructor-arg index="0" type="com.rory.services.pcrf.simulator.CustomGxSessionIdCacheImpl">
        <bean factory-bean="PcrfSimulator" factory-method="getGxSessionIdCache">
        </bean>
    </constructor-arg>       
</bean>
Run Code Online (Sandbox Code Playgroud)

IE浏览器.我首先创建一个bean,然后尝试将该bean的方法调用结果传递给第二个bean的(CacheHandler)构造函数.

这是CacheHandler的开始:

    @Controller
    public class CacheHandler {

    private final CustomGxSessionIdCacheImpl gxSessionIdCache;

    public CacheHandler(CustomGxSessionIdCacheImpl gxSessionIdCache) {
        this.gxSessionIdCache = gxSessionIdCache;
    }
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cacheHandler' defined in URL [jar:file:/users/rtorney/Documents/apache-tomcat-7.0.25/webapps/PCRFSimulator-4.0/WEB-INF/lib/PCRFSimulator-4.0.jar!/com/rory/services/pcrf/simulator/handlers/CacheHandler.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.rory.services.pcrf.simulator.handlers.CacheHandler]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.rory.services.pcrf.simulator.handlers.CacheHandler.<init>()
Run Code Online (Sandbox Code Playgroud)

任何帮助深表感谢!

sou*_*eck 20

您应该在xml中定义bean或者注释它们,而不是两者(如果只是为了避免像你得到的那样的错误).

这里的问题是你没有自动装配构造函数args,所以spring不知道如何处理你的控制器.它知道它必须创建一个bean(@Controller注释),但它不知道如何(没有默认值,也没有autowired构造函数).

您可以尝试执行以下操作:

@Controller
public class CacheHandler {

private final CustomGxSessionIdCacheImpl gxSessionIdCache;

@Autowired 
public CacheHandler(CustomGxSessionIdCacheImpl gxSessionIdCache) {
   this.gxSessionIdCache = gxSessionIdCache;
} 
Run Code Online (Sandbox Code Playgroud)

然后在xml中:

<bean id="gxSessionIdCache"
  factory-bean="PcrfSimulator"
  factory-method="getGxSessionIdCache"/>
Run Code Online (Sandbox Code Playgroud)

因此它将自动装配构造函数参数.

另一种选择是简单地创建默认构造函数和autowire gxSessionIdCache属性.