Spring mvc cannot autowire dao classes in junit tests - spring-mvc

I have a spring mvc web application configured using javaconfig and I am trying to autowire my dao classes on the junit test class and I am using #EnableWebMvc for the servlet config, but it gives me the following exception:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.jahidul.islam.test.tests.TestJunit': Unsatisfied dependency expressed through field 'strengthDao'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.jahidul.islam.dao.StrengthDao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
My Test Class which is used for the junit test:
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextHierarchy({
#ContextConfiguration(loader=AnnotationConfigWebContextLoader.class),
#ContextConfiguration(classes=WebAppInitializer.class)
})
public class TestJunit {
#Autowired
WebApplicationContext context;
#Autowired
StrengthDao strengthDao;
#Test
public void test() {
System.out.println(strengthDao.getStrength(1));
}
}
My WebAppInitializer Class which initializes all the configurations:
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] {WebAppBeanConfig.class, WebAppDaoConfig.class, WebAppServiceConfig.class, WebSecurityConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {WebAppServletConfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
#Override
protected Filter[] getServletFilters() {
return new Filter[]{new HiddenHttpMethodFilter()};
}
#Override
protected DispatcherServlet createDispatcherServlet(WebApplicationContext servletAppContext) {
final DispatcherServlet dispatcherServlet = (DispatcherServlet) super.createDispatcherServlet(servletAppContext);
dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
return dispatcherServlet;
}
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
servletContext.setInitParameter("spring.profiles.active", "production");
}
}
My Dao Class which is used to fetch data from mysql database using hibernate:
#Component("strengthDao")
#Transactional
public class StrengthDao {
#Autowired
private SessionFactory sessionFactory;
private Session session() {
return sessionFactory.getCurrentSession();
}
public List<Strength> getAllStrengths(int perPage, int offset) {
CriteriaBuilder builder = session().getCriteriaBuilder();
CriteriaQuery<Strength> criteriaQuery = builder.createQuery(Strength.class);
Root<Strength> root = criteriaQuery.from(Strength.class);
criteriaQuery.select(root);
return (List<Strength>) session().createQuery(criteriaQuery).setFirstResult(offset).setMaxResults(perPage).getResultList();
}
public long strengthCount() {
CriteriaBuilder builder = session().getCriteriaBuilder();
CriteriaQuery<Long> criteriaQuery = builder.createQuery(Long.class);
Root<Strength> root = criteriaQuery.from(Strength.class);
criteriaQuery.select(builder.count(root));
return (long) session().createQuery(criteriaQuery).getSingleResult();
}
public void saveOrUpdateStrength(Strength strength) {
session().saveOrUpdate(strength);
}
public Strength getStrength(int id) {
return (Strength) session().get(Strength.class, id);
}
public void deleteStrength(Strength strength) {
session().delete(strength);
}
}

Either add componentScan annotation to TestJunit class to auto detect #Repository components.
Or create a java config bean in TestJunit class using #Bean annotation like
#Bean
public StrengthDao StrengthDao(){
return new StrengthDao ();
}

Related

How to bind a Store using Spring Cloud Stream and Kafka?

I'd like to use a Kafka state store of type KeyValueStore in a sample application using the Kafka Binder of Spring Cloud Stream.
According to the documentation, it should be pretty simple.
This is my main class:
#SpringBootApplication
public class KafkaStreamTestApplication {
public static void main(String[] args) {
SpringApplication.run(KafkaStreamTestApplication.class, args);
}
#Bean
public BiFunction<KStream<String, String>, KeyValueStore<String,String>, KStream<String, String>> process(){
return (input,store) -> input.mapValues(v -> v.toUpperCase());
}
#Bean
public StoreBuilder myStore() {
return Stores.keyValueStoreBuilder(
Stores.persistentKeyValueStore("my-store"), Serdes.String(),
Serdes.String());
}
}
I suppose that the KeyValueStore should be passed as the second parameter of the "process" method, but the application fails to start with the message below:
Caused by: java.lang.IllegalStateException: No factory found for binding target type: org.apache.kafka.streams.state.KeyValueStore among registered factories: channelFactory,messageSourceFactory,kStreamBoundElementFactory,kTableBoundElementFactory,globalKTableBoundElementFactory
at org.springframework.cloud.stream.binding.AbstractBindableProxyFactory.getBindingTargetFactory(AbstractBindableProxyFactory.java:82) ~[spring-cloud-stream-3.0.3.RELEASE.jar:3.0.3.RELEASE]
at org.springframework.cloud.stream.binder.kafka.streams.function.KafkaStreamsBindableProxyFactory.bindInput(KafkaStreamsBindableProxyFactory.java:191) ~[spring-cloud-stream-binder-kafka-streams-3.0.3.RELEASE.jar:3.0.3.RELEASE]
at org.springframework.cloud.stream.binder.kafka.streams.function.KafkaStreamsBindableProxyFactory.afterPropertiesSet(KafkaStreamsBindableProxyFactory.java:103) ~[spring-cloud-stream-binder-kafka-streams-3.0.3.RELEASE.jar:3.0.3.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1855) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1792) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
I found the solution about how to use a store reading an unit test in Spring Cloud Stream.
The code below is how I applied that solution to my code.
The transformer uses the Store provided by Spring bean method "myStore"
#SpringBootApplication
public class KafkaStreamTestApplication {
public static final String MY_STORE_NAME = "my-store";
public static void main(String[] args) {
SpringApplication.run(KafkaStreamTestApplication.class, args);
}
#Bean
public Function<KStream<String, String>, KStream<String, String>> process2(){
return (input) -> input.
transformValues(() -> new MyValueTransformer(), MY_STORE_NAME);
}
#Bean
public StoreBuilder<?> myStore() {
return Stores.keyValueStoreBuilder(
Stores.persistentKeyValueStore(MY_STORE_NAME), Serdes.String(),
Serdes.String());
}
}
public class MyValueTransformer implements ValueTransformer<String, String> {
private KeyValueStore<String,String> store;
private ProcessorContext context;
#Override
public void init(ProcessorContext context) {
this.context = context;
store = (KeyValueStore<String, String>) this.context.getStateStore(KafkaStreamTestApplication.MY_STORE_NAME);
}
#Override
public String transform(String value) {
String tValue = store.get(value);
if(tValue==null) {
store.put(value, value.toUpperCase());
}
return tValue;
}
#Override
public void close() {
if(store!=null) {
store.close();
}
}
}

Spring MVC java based configuration without xml not working

I am trying to create sample spring MVC application with java based configuration with annotation so I am not using any XML file for configuration.
I have below Controller, Dispatcher servlet initializer class.
My JSP file is home.jsp which is present inside WEB-INF/view folder. Kindly help.
#Controller
public class DemoController {
#RequestMapping("/")
public String showHome(Model model) {
return "home";
}
}
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.luv2code.springsecurity")
public class DemoAppConfig {
// define a bean for ViewResolver
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
public class MySpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{DemoAppConfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}

configure MappingJacksonHttpMessageConverter getting BeanCreationException

Error log:
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'converter' defined in class path resource
[...../spring/controller/PsvJackson2HttpMessageConverter.class]:
No matching factory method found: factory bean 'psvJackson2HttpMessageConverter';
factory method 'converter()'.
Check that a method with the specified name exists and that it is non-static.
And here is the configuration class:
#Configuration
public class PsvJackson2HttpMessageConverter extends WebMvcConfigurationSupport {
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(converter());
converters.add(new ByteArrayHttpMessageConverter());
converters.add(new StringHttpMessageConverter());
super.addDefaultHttpMessageConverters(converters);
}
#Bean
MappingJackson2HttpMessageConverter converter() {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
converter.setObjectMapper(objectMapper);
return converter;
}
}
Don't know what is wrong here.
Here is the thing which you can do:
Create a configuration class, which registers/maps the converters.
Create custom converter class.
For example, here is the config class:
#EnableWebMvc
#Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void configureMessageConverters(final List<HttpMessageConverter<?>> converters) {
converters.add(new CustomMappingJackson2HttpMessageConverter());
super.configureMessageConverters(converters);
}
}
and here is the converter class:
public class CustomMappingConverter extends AbstractJackson2HttpMessageConverter {
public CustomMappingConverter(final ObjectMapper objectMapper){
super(objectMapper, MediaType.APPLICATION_JSON, new MediaType("application", "*+json"), new MediaType("application", "jsonp"));
}
private String jsonPrefix;
public CustomMappingConverter() {
this(Jackson2ObjectMapperBuilder.json().build());
}
public void setJsonPrefix(final String jsonPrefix) {
this.jsonPrefix = jsonPrefix;
}
public void setPrefixJson(final boolean prefixJson) {
jsonPrefix = prefixJson ? ")]}', " : null;
}
#Override
protected void writePrefix(final JsonGenerator generator, final Object object) throws IOException {
if (jsonPrefix != null) {
generator.writeRaw(jsonPrefix);
}
final String jsonpFunction =
object instanceof MappingJacksonValue ? ((MappingJacksonValue) object).getJsonpFunction() : null;
if (jsonpFunction != null) {
generator.writeRaw("/**/");
generator.writeRaw(jsonpFunction + "(");
}
}
#Override
protected void writeSuffix(final JsonGenerator generator, final Object object) throws IOException {
final String jsonpFunction =
object instanceof MappingJacksonValue ? ((MappingJacksonValue) object).getJsonpFunction() : null;
if (jsonpFunction != null) {
generator.writeRaw(");");
}
}
}

Autowired in Spring MVC getting error : Error creating bean with name 'userService': Injection of autowired dependencies

I am having this error for few days and seem to get no luck. Tried googling but still can't get it working. Looking on the log it keeps on telling me that there is something wrong with my "Injection of autowired dependencies" but I just can't get it. Hope to hear from you.
Error Logs.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.sesame.repository.UserRepository com.sesame.service.UserService.userRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.sesame.repository.UserRepository] 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)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.context.web.SpringBootServletInitializer.run(SpringBootServletInitializer.java:117)
at org.springframework.boot.context.web.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:108)
at org.springframework.boot.context.web.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:68)
at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:175)
.......
Controller class
#Controller
#RequestMapping(value = "/protected/users")
public class UsersControl {
private static final String DEFAULT_PAGE_DISPLAYED_TO_USER = "0";
#Autowired
private UserService userService;
#Autowired
private MessageSource messageSource;
#Value("5")
private int maxResults;
#RequestMapping(method = RequestMethod.GET)
public ModelAndView welcome() {
return new ModelAndView("contactsList");
}
#RequestMapping(method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<?> listAll(#RequestParam int page, Locale locale) {
return createListAllResponse(page, locale);
}
private UserListVO listAll(int page) {
return userService.findAll(page, maxResults);
}
private ResponseEntity<UserListVO> returnListToUser(UserListVO contactList) {
return new ResponseEntity<UserListVO>(contactList, HttpStatus.OK);
}
private ResponseEntity<?> createListAllResponse(int page, Locale locale) {
return createListAllResponse(page, locale, null);
}
private ResponseEntity<?> createListAllResponse(int page, Locale locale, String messageKey) {
UserListVO UserListVO = listAll(page);
addActionMessageToVO(UserListVO, locale, messageKey, null);
return returnListToUser(UserListVO);
}
private UserListVO addActionMessageToVO(UserListVO UserListVO, Locale locale, String actionMessageKey, Object[] args) {
if (StringUtils.isEmpty(actionMessageKey)) {
return UserListVO;
}
UserListVO.setActionMessage(messageSource.getMessage(actionMessageKey, args, null, locale));
return UserListVO;
}
}
service is existing:
#Service("userService")
#Transactional
public class UserService {
#Autowired
private UserRepository userRepository;
#Transactional(readOnly = true)
public UserListVO findAll(int page, int maxResults) {
Page<User> result = executeQueryFindAll(page, maxResults);
if(shouldExecuteSameQueryInLastPage(page, result)){
int lastPage = result.getTotalPages() - 1;
result = executeQueryFindAll(lastPage, maxResults);
}
return buildResult(result);
}
private Page<User> executeQueryFindAll(int page, int maxResults) {
final PageRequest pageRequest = new PageRequest(page, maxResults, sortByNameASC());
System.out.println("Now in ExectueQuery"+pageRequest);
return userRepository.findAll(pageRequest);
}
private Sort sortByNameASC() {
return new Sort(Sort.Direction.ASC, "name");
}
private UserListVO buildResult(Page<User> result) {
return new UserListVO(result.getTotalPages(), result.getTotalElements(), result.getContent());
}
private boolean shouldExecuteSameQueryInLastPage(int page, Page<User> result) {
return isUserAfterOrOnLastPage(page, result) && hasDataInDataBase(result);
}
private boolean isUserAfterOrOnLastPage(int page, Page<User> result) {
return page >= result.getTotalPages() - 1;
}
private boolean hasDataInDataBase(Page<User> result) {
return result.getTotalElements() > 0;
}
}
I've added the repository
#Repository("userRepository")
public interface UserRepository extends JpaRepository<User, Integer> {
Page<User> findByUserNameLike(Pageable pageable, String UserName);
}
WebConfiguration
#Configuration
#EnableWebMvc
#ComponentScan(basePackages="com.sesame")
#EnableAutoConfiguration
#PropertySource(value = { "classpath:application.properties" })
#EnableScheduling
#EnableAspectJAutoProxy
#EnableCaching
public class WebConfig extends WebMvcConfigurerAdapter {
#Autowired
private Environment env;
#Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
#Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver resolver = new SessionLocaleResolver();
resolver.setDefaultLocale(Locale.ENGLISH);
return resolver;
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor changeInterceptor = new LocaleChangeInterceptor();
changeInterceptor.setParamName("language");
registry.addInterceptor(changeInterceptor);
}
#Bean
public InternalResourceViewResolver getInternalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix("/");
return resolver;
}
#Bean public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
#Bean
public JavaMailSenderImpl javaMailSenderImpl() {
JavaMailSenderImpl mailSenderImpl = new JavaMailSenderImpl();
mailSenderImpl.setHost(env.getProperty("smtp.host"));
mailSenderImpl.setPort(env.getProperty("smtp.port", Integer.class));
mailSenderImpl.setProtocol(env.getProperty("smtp.protocol"));
mailSenderImpl.setUsername(env.getProperty("smtp.username"));
mailSenderImpl.setPassword(env.getProperty("smtp.password"));
Properties javaMailProps = new Properties();
javaMailProps.put("mail.smtp.auth", true);
javaMailProps.put("mail.smtp.starttls.enable", true);
mailSenderImpl.setJavaMailProperties(javaMailProps);
return mailSenderImpl;
}
#Bean public CacheManager cacheManager() {
return new ConcurrentMapCacheManager();
}
#Bean
public ServletRegistrationBean dispatcherRegistration() {
ServletRegistrationBean registration = new ServletRegistrationBean(
dispatcherServlet());
registration.addUrlMappings("/");
registration.addUrlMappings("*.pdf");
registration.addUrlMappings("*.json");
registration.addUrlMappings("*.js");
registration.addUrlMappings("*.xml");
registration.addUrlMappings("*.css");
return registration;
}
#Bean(name = DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
public DispatcherServlet dispatcherServlet() {
return new DispatcherServlet();
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/pdfs/**").addResourceLocations(
"/WEB-INF/pdf/");
registry.addResourceHandler("/resources/js/**").addResourceLocations(
"/WEB-INF/resources/js/");
registry.addResourceHandler("/resources/css/**").addResourceLocations(
"/WEB-INF/resources/css/");
registry.addResourceHandler("/resources/img/**").addResourceLocations(
"/WEB-INF/resources/img/");
}
#Bean
public ViewResolver tilesViewResolver() {
return new TilesViewResolver();
}
#Bean
public TilesConfigurer tilesConfigurer() {
TilesConfigurer tiles = new TilesConfigurer();
tiles.setDefinitions(new String[] {"/WEB-INF/tiles.xml"});
tiles.setCheckRefresh(true);
return tiles;
}
}
Create a JPA Config Class as below :
#Configuration
#EnableJpaRepositories(basePackages="com.sesame.repository")
#EntityScan(basePackages="com.sesame.model")
public class JpaConfiguration {
}

Spring MVC doesn't handle the error came from hibernate validator

I create form and controller this form have some validation constrains using Hibernate validator. I face problem when starting test the validation constrains but I got Blue Exception page with the attributemodel with the rejected.
This the configuration
#Configuration
#ComponentScan(basePackages = {"com.whatever.core.web"})
#EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurationSupport {
private static final String MESSAGE_SOURCE = "/WEB-INF/classes/messages";
private static final String TILES = "/WEB-INF/tiles/tiles.xml";
private static final String VIEWS = "/WEB-INF/views/**/views.xml";
private static final String RESOURCES_HANDLER = "/resources/";
private static final String RESOURCES_LOCATION = RESOURCES_HANDLER + "**";
#Override
public RequestMappingHandlerMapping requestMappingHandlerMapping() {
RequestMappingHandlerMapping requestMappingHandlerMapping = super.requestMappingHandlerMapping();
requestMappingHandlerMapping.setUseSuffixPatternMatch(false);
requestMappingHandlerMapping.setUseTrailingSlashMatch(false);
return requestMappingHandlerMapping;
}
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new MappingJacksonHttpMessageConverter());
}
#Bean(name = "messageSource")
public MessageSource configureMessageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename(MESSAGE_SOURCE);
messageSource.setCacheSeconds(5);
return messageSource;
}
#Bean
public TilesViewResolver configureTilesViewResolver() {
return new TilesViewResolver();
}
#Bean
public TilesConfigurer configureTilesConfigurer() {
TilesConfigurer configurer = new TilesConfigurer();
configurer.setDefinitions(new String[] {TILES, VIEWS});
return configurer;
}
#Override
public Validator getValidator() {
LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
validator.setValidationMessageSource(configureMessageSource());
return validator;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(RESOURCES_HANDLER).addResourceLocations(RESOURCES_LOCATION);
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
and the controller here
if(result.hasErrors()){
return null; OR "view name"
}
User user = new User();
user.setUsername(userModel.getUsername());
user.setFirstName(userModel.getFirstName());
user.setLastName(userModel.getLastName());
user.setGender(userModel.getGender());
user.setLocation(userModel.getLocation());
user.setPassword(passwordEncoder.encodePassword(userModel.getPassword(),null));
userRepository.save(user);
doAutoLogin(userModel.getUsername(),userModel.getPassword(),request);
return "redirect:/home";
NOTE: I use springMVC, spring security, tiles, and hibernate validator
I used SpringMVC with hibernate validator with XML configuration and portal environment and work fine I don't know what the wrong here!!
I Found the issue! the signature of the method controller should be like this
public String signup(#ModelAttribute("userModel") #Valid SignupForm userModel,BindingResult result,HttpServletRequest request,HttpServletResponse response,ModelMap model)
as what I read in sprinsource forum, the BindingResult should follow the modelAttribute and work find. I didn't find any official documentation for this but its work now.
to see the thread of springsource forum check this link http://forum.springsource.org/showthread.php?85815-BindException-Thrown-on-bind-errors-(instead-of-returning-errors-to-controller-method

Resources