Do We need to write a bean in spring-config.xml if I use @Autowired? if yes why? I have this following example
@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;
}
}
Spring-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>
When I try to execute the above program I am getting below exception:
ERROR [http-nio-8080-exec-2] [/passwordcheck].[password-check] - Allocate exception for servlet password-check org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [passwordcheck.service.PasswordValidatonServiceImpl] 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)}
If I add bean in spring-config xml I am able to resolve.
My question is do we need to write bean for my ServiceClass which is auto wired in my controller class?