无法实例化[..]:找不到默认构造函数;

时间:2016-08-13 20:36:00

标签: spring

我得到了:

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mz.server.rest.braintree.webhooks.SubscriptionWebhook]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.mz.server.rest.braintree.webhooks.SubscriptionWebhook.<init>()
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:85)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1098)
    ... 22 more

即使我在applicatioContext-restapi.xml文件中定义了这个构造函数:

<bean id="subscriptionWebhook" class="com.mz.server.rest.braintree.webhooks.SubscriptionWebhook">
    <constructor-arg ref="dslContext" />
</bean>

知道为什么吗?

@RestController
public class SubscriptionWebhook {

    private final static Logger LOGGER = Logger.getLogger(SubscriptionWebhook.class.getName());

    private AdminService adminService;      

    public SubscriptionWebhook(DSLContext ctx) {
        this.adminService = new AdminService(ctx);
    }
}

2 个答案:

答案 0 :(得分:1)

从Spring 3(ish)开始,您可以通过将@Component注释应用于类来配置容器。 @Controller注释定义如下:

@Target(value=TYPE)
@Retention(value=RUNTIME)
@Documented
@Component
public @interface Controller

这意味着由它注释的类也将被拾取。而RestController只是ControllerResponseBody放在一起。

无论如何,正如您在评论中承认的那样,您已启用了组件扫描,并且xml中的配置在这种情况下无法获取。

您可以做的是将xml配置转换为基于注释的注入,如下所示:

@RestController
public class SubscriptionWebhook {

    private final static Logger LOGGER = Logger.getLogger(SubscriptionWebhook.class.getName());

    private AdminService adminService;      

    public SubscriptionWebhook(@Qualifier("dslContext") DSLContext ctx) {
        this.adminService = new AdminService(ctx);
    }
}

Qualifier注释将在容器中查找名为/ dslContext的bean,并将其注入构造函数中。或者,您可以使用javax.inject Named注释,或者如果这是唯一具有该类型的bean,那么Spring @Autowired或JSR-330&{39} {{1} }。

答案 1 :(得分:0)

注释@RestController由spring自动检测。 Spring将为您创建一个bean,因此您不应该在xml中添加bean定义,因为它会创建第二个bean。如果要将另一个bean注入控制器,只需使用@Autowired。所以你的案例中的解决方案是:

  1. 删除&#34; subscriptionWebhook&#34;来自xml的bean定义
  2. 在SubscriptionWebhook构造函数
  3. 上添加@Autowired
相关问题