【问题标题】:Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:注入自动装配的依赖项失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:
【发布时间】:2012-07-30 08:05:12
【问题描述】:

我正在使用 Spring、Hibernate、Struts 和 Maven 创建 Web 应用程序。

运行mvn clean install 命令时出现以下错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.project.action.PasswordHintActionTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.project.action.PasswordHintAction com.project.action.PasswordHintActionTest.action; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.project.action.PasswordHintAction] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

以下是具有Autowired依赖的类:

import com.opensymphony.xwork2.Action;
import org.project.model.User;
import org.proejct.service.UserManager;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.subethamail.wiser.Wiser;

import static org.junit.Assert.*;
public class PasswordHintActionTest extends BaseActionTestCase {
    @Autowired
    private PasswordHintAction action;
    @Autowired
    private UserManager userManager;

    @Test
    public void testExecute() throws Exception {
        // start SMTP Server
        Wiser wiser = new Wiser();
        wiser.setPort(getSmtpPort());
        wiser.start();

        action.setUsername("user");
        assertEquals("success", action.execute());
        assertFalse(action.hasActionErrors());

        // verify an account information e-mail was sent
        wiser.stop();
        assertTrue(wiser.getMessages().size() == 1);

        // verify that success messages are in the request
        assertNotNull(action.getSession().getAttribute("messages"));
    }


}

我的applicationcontext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
       default-lazy-init="true">

    <!-- Activates scanning of @Autowired -->
    <context:annotation-config/>

    <!-- Activates scanning of @Repository and @Service -->
    <context:component-scan base-package="com.project"/>

    <!-- Compass Search Section -->
    <!-- Compass Bean, automatically scanning for searchable classes within the model -->
    <!-- Hooks into Spring transaction management and stores the index on the file system -->
    <bean id="compass" class="org.compass.spring.LocalCompassBean">
        <property name="mappingScan" value="org.project"/>
        <property name="postProcessor" ref="compassPostProcessor"/>
        <property name="transactionManager" ref="transactionManager" />
        <property name="settings">
            <map>
                <entry key="compass.engine.connection" value="target/test-index" />
            </map>
        </property>
    </bean>

我已添加到我的上下文配置中以扫描 Autowired 依赖项。但我不确定为什么它仍然给出这个异常。

我也尝试通过以下方式添加它,但我仍然遇到同样的异常

<context:component-scan base-package="com.project.*"/>

更新:

下面是密码提示动作

import org.project.model.User;
import com.project.webapp.util.RequestUtil;
import org.springframework.mail.MailException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;


public class PasswordHintAction extends BaseAction {
    private static final long serialVersionUID = -4037514607101222025L;
    private String username;

    /**
     * @param username The username to set.
     */
    public void setUsername(String username) {
        this.username = username;
    }

    /**
     * Execute sending the password hint via e-mail.
     *
     * @return success if username works, input if not
     */
    public String execute() {
        List<Object> args = new ArrayList<Object>();

        // ensure that the username has been sent
        if (username == null) {
            log.warn("Username not specified, notifying user that it's a required field.");

            args.add(getText("user.username"));
            addActionError(getText("errors.requiredField", args));
            return INPUT;
        }

        if (log.isDebugEnabled()) {
            log.debug("Processing Password Hint...");
        }

        // look up the user's information
        try {
            User user = userManager.getUserByUsername(username);
            String hint = user.getPasswordHint();

            if (hint == null || hint.trim().equals("")) {
                log.warn("User '" + username + "' found, but no password hint exists.");
                addActionError(getText("login.passwordHint.missing"));
                return INPUT;
            }

            StringBuffer msg = new StringBuffer();
            msg.append("Your password hint is: ").append(hint);
            msg.append("\n\nLogin at: ").append(RequestUtil.getAppURL(getRequest()));

            mailMessage.setTo(user.getEmail());
            String subject = '[' + getText("webapp.name") + "] " + getText("user.passwordHint");
            mailMessage.setSubject(subject);
            mailMessage.setText(msg.toString());
            mailEngine.send(mailMessage);

            args.add(username);
            args.add(user.getEmail());

            saveMessage(getText("login.passwordHint.sent", args));
        } catch (UsernameNotFoundException e) {
            log.warn(e.getMessage());
            args.add(username);
            addActionError(getText("login.passwordHint.error", args));
            getSession().setAttribute("errors", getActionErrors());
            return INPUT;
        } catch (MailException me) {
            addActionError(me.getCause().getLocalizedMessage());
            getSession().setAttribute("errors", getActionErrors());
            return INPUT;
        }

        return SUCCESS;
    }
}

更新 2:

applicationContext-struts.xml:

<bean id="passwordHintAction" class="com.project.action.PasswordHintAction" scope="prototype">
    <property name="userManager" ref="userManager"/>
    <property name="mailEngine" ref="mailEngine"/>
    <property name="mailMessage" ref="mailMessage"/>
</bean>

【问题讨论】:

  • 我只看到你的上下文文件的一部分,它不包含任何类型的 bean PasswordHintAction
  • @Klits:我编辑了我的答案,看看。
  • @Kltis: 你能在这里添加你的 web.xml 代码吗.. 谢谢

标签: java spring hibernate spring-mvc struts


【解决方案1】:

使用下面给出的组件扫描,如果com.project.action.PasswordHintAction 使用原型注释进行注释

<context:component-scan base-package="com.project.action"/>

编辑

我看到了您的问题,在 PasswordHintActionTest 中,您正在自动装配 PasswordHintAction。但是您没有为 PasswordHintAction 创建 bean 配置以进行自动装配。添加一个原型注释(@Component, @Service, @Controller)到PasswordHintAction like

@Component
public class PasswordHintAction extends BaseAction {
    private static final long serialVersionUID = -4037514607101222025L;
    private String username;

或在applicationcontext.xml中创建xml配置

<bean id="passwordHintAction" class="com.project.action.PasswordHintAction" />

【讨论】:

  • 其实我有这个配置是单独的配置文件,称为applicationContext-struts.xml。我已经用这个更新更新了我的问题。但即使这样我也得到了这个错误
  • 感谢您的回答,我没有将 applicationContext-struts.xml 链接到我的 web.xml 文件中。这就是问题所在。无论如何,您的回答帮助我进入了这个解决方案。
【解决方案2】:

您需要为自动装配提供候选人。这意味着必须知道 PasswordHint 的实例以它可以猜测它必须引用它的方式弹出。

请提供 PasswordHint 的类头和/或该类的 spring bean 定义以获得进一步帮助。

换个名字试试

PasswordHintAction action;

PasswordHintAction passwordHintAction;

使其与 bean 定义相匹配。

【讨论】:

  • 感谢您的努力,无论如何,问题是我没有添加 applicationContaxt-strtus.xml,它的密码提示 bean 定义链接到上下文参数下的 web.xml 文件。
【解决方案3】:

在 bean.xml 文件或任何其他配置文件中添加 bean 声明。它将解决错误

<bean  class="com.demo.dao.RailwayDao"></bean>
<bean  class="com.demo.service.RailwayService"></bean>
<bean  class="com.demo.model.RailwayReservation"></bean>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-18
    • 2018-11-01
    • 2015-02-28
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多