我有一个 Spring 控制器,我认为它会根据我在调试代码时看到的对象 ID 多次实例化。
控制器:
@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");
}
}
弹簧配置文件:
<?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>
当我通过 UserController 发出请求时意识到 userService 为空时,我注意到了这个问题。然而; 当我设置断点时,我看到 userService 确实设置在 UserController 的另一个实例中。