如果我使用@Autowired Annotation,我们是否需要在spring-cofig.xml中创建一个bean

时间:2017-09-06 14:15:51

标签: java spring spring-mvc autowired

如果我使用@Autowired,我们是否需要在spring-config.xml中编写一个bean?如果是,为什么?我有以下示例

@Controller
public class PasswordValidationController {

    private static final String ERRORS = "errors";
    private static final String SUCCESS = "success";
    private static final String PASSWORD = "password";
    @Autowired
    PasswordValidatonServiceImpl passwordValidatorService;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ModelAndView passWordRequestPage() {
        return new ModelAndView(PASSWORD);

    }

    @RequestMapping(value = "/validatepassword", method = RequestMethod.POST)
    public ModelAndView passWordCheck(
            @ModelAttribute(PASSWORD) Password password, BindingResult result) {

        List<String> validate = passwordValidatorService.validatePassword(password
                .getPassword());

        if (!validate.isEmpty()) {
            return invalidPassword(validate);
        } else {
            ModelAndView model = new ModelAndView(SUCCESS);
            return model;
        }

    }

    private ModelAndView invalidPassword(List<String> validate) {
        ModelAndView model = new ModelAndView(PASSWORD);
        model.addObject(ERRORS, validate);
        return model;
    }

}

弹簧config.xml中:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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-3.0.xsd
    http://www.springframework.org/schema/mvc   http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <context:component-scan base-package="passwordcheck.controller" />
    <mvc:annotation-driven />
    <context:annotation-config/>
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/Jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

当我尝试执行上述程序时,我遇到异常:

  

ERROR [http-nio-8080-exec-2] [/passwordcheck].[password-check] -   为servlet密码检查分配异常   org.springframework.beans.factory.NoSuchBeanDefinitionException:没有   合格的bean类型   找到[passwordcheck.service.PasswordValidatonServiceImpl]   依赖:预计至少有1个bean有资格成为autowire   这种依赖的候选人。依赖注释:   {@ org.springframework.beans.factory.annotation.Autowired(所需=真)}

如果我在spring-config xml中添加bean,我就能解析。

我的问题是我们是否需要为我的ServiceClass编写bean,它在我的控制器类中是自动连接的?

0 个答案:

没有答案