Tuesday, 17 September 2013

Spring controller not created as singleton

Spring controller not created as singleton

I have a Spring controller that I think is getting instantiated more than
once based on the object ids I see when I debug through the code.
Controller:
@Controller
@RequestMapping("/services/user")
public class UserController{
private UserService userService;
public void setUserService(UserService userService) {
this.userService = userService;
}
public UserService getUserService() {
return userService;
}
@RequestMapping(method = RequestMethod.POST, value = "/createUser")
public @ResponseBody String createUser(@RequestBody User user) throws
UserNotCreatedException {
try {
userService.createUser(user);
return user.getEmail();
} catch (Exception e) {
e.printStackTrace();
throw new UserNotCreatedException("User not created");
}
}
Spring configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<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"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
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">
<!-- Scans the classpath of this application for @Components to deploy as
beans -->
<context:component-scan base-package="com.xyz.controller" />
<context:annotation-config />
<bean id="userController" class="com.xyz.UserController">
<property name="userService" ref="userService" />
</bean>
<bean id="userService" class="com.xyz.UserServiceImpl">
<property name="userDao" ref="userDaoMysql" />
</bean>
<bean id="userDaoMysql" class="com.xyz.UserDaoImpl" >
<property name="dataSource" ref="dataSource"></property>
<property name="template" ref="jdbcTemplate"></property>
</bean>
</beans>
I noticed the problem when I realized that userService is null when I make
a request that goes through UserController. However; when I put break
points, I see that userService does get set in another instance of
UserController.

No comments:

Post a Comment