2016-08-13 90 views
0

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

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); 
    } 
} 
+1

错误是'com.mz.server.rest.UserVerificationResource',而不是'com.mz.server.rest.braintree.webhooks.SubscriptionWebhook' – mszymborski

+0

@mszymborski感谢提示和抱歉的困惑。这是一个复制和粘贴错误。我有一个以上的对象,我尝试这样使用。我纠正了我的帖子.. – displayname

+0

你有没有试过简单地在控制器中使用注释注入它? @Inject/@ Autowired – mszymborski

回答

1

由于春季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注释会在容器中寻找与名称/ ID dslContext一个bean和它注入构造函数。或者,您可以使用javax.injectNamed注释,或者如果这是唯一具有该类型的bean,则可以使用Spring的@Autowired或JSR-330的@Inject

+1

这很整洁!谢谢你帮助我! :) – displayname

0

Annotation @RestController在春天被自动检测。 Spring会为你创建一个bean,所以你不应该在xml中添加bean定义,因为它会创建第二个bean。如果你想使用@Autowired将另一个bean注入控制器。所以你的情况的解决方案是:

  1. 删除 “subscriptionWebhook” bean定义从XML
  2. 添加@Autowired上SubscriptionWebhook构造
相关问题