我正在开发我的第一个Spring MVC应用程序,但我遇到了一个例外。
该应用程序有一个Offer类,它有一个User类型的私有成员,显然是另一个类。
我正在使用注释配置。我在两个类构造函数中都有一个sys。我可以看到,在所有场合都创建了一个offer对象,还创建了一个用户对象,以便自动装配工作。
但是,控制器的doCreate方法不是这种情况。将商品对象传递给它以验证并绑定到HTML表单,但Spring不会创建其用户对象。
因此,我在这一行得到一个NullPointerException:
offer.getUser().setUsername(username);
因此,在这种情况下,为什么Spring在使用Offer对象的所有其他情况下都能正常工作时,不会创建Offer对象的依赖User对象。是什么影响了这种行为?
控制器类(有问题的方法在最后)
package com.offers.controllers;
import java.security.Principal;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.offers.dao.Offer;
import com.offers.service.OffersService;
@Controller
public class OffersController {
private OffersService offersService;
@Autowired
public void setOffersService(OffersService offersService) {
this.offersService = offersService;
}
@RequestMapping("/offers")
public String showOffers(Model model){
//offersService.throwTestException();
List<Offer> offers = offersService.getCurrent();
model.addAttribute("offers", offers);
return "offers";
}
@RequestMapping("/createoffer")
public String createOffer(Model model){
model.addAttribute("offer", new Offer());
return "createoffer";
}
@RequestMapping(value = "/docreate", method = RequestMethod.POST)
public String doCreate(Model model, @Valid Offer offer, BindingResult result, Principal principal) {
if (result.hasErrors()) {
return "createoffer";
}
String username = principal.getName();
offer.getUser().setUsername(username);
offersService.create(offer);
return "offercreated";
}
}
Offer类(用户setter方法紧跟在构造函数之后)
package com.offers.dao;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.offers.validation.HasSpace;
@Component
public class Offer {
// MEMBERS
private int id;
@NotNull
@HasSpace
@Size(min = 5, max = 100, message = "The text must be between 5 and 100 characters.")
private String text;
private User user;
// CONSTRUCTORS
public Offer() {
System.out.println("************* offer created");
}
public Offer(int id, User user, String text) {
this.id = id;
this.user = user;
this.text = text;
}
public Offer(String text, User user) {
this.user = user;
this.text = text;
}
// GETTERS AND SETTERS
@Autowired
public void setUser(User user) {
this.user = user;
}
public String getUsername(){
return user.getUsername();
}
public void setId(int id) {
this.id = id;
}
public void setText(String text) {
this.text = text;
}
public int getId() {
return id;
}
public String getText() {
return text;
}
public User getUser() {
return user;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((text == null) ? 0 : text.hashCode());
result = prime * result + ((user == null) ? 0 : user.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Offer other = (Offer) obj;
if (text == null) {
if (other.text != null)
return false;
} else if (!text.equals(other.text))
return false;
if (user == null) {
if (other.user != null)
return false;
} else if (!user.equals(other.user))
return false;
return true;
}
@Override
public String toString() {
return "Offer [id=" + id + ", text=" + text + ", user=" + user + "]";
}
}
用户类
package com.offers.dao;
import javax.annotation.Resource;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.offers.validation.ValidEmail;
@Component
@Scope("prototype")
public class User {
// MEMBERS
@NotBlank(message="Username cannot be blank")
@Size(min=8, max=15)
@Pattern(regexp="^\\w{8,}$", message="Username can only consists of numbers, letters and underscore")
private String username;
@NotBlank(message="Password cannot be blank")
@Pattern(regexp="^\\S+$", message="Password must not contain spaces")
@Size(min=8, max=15, message="Password must be between 8 and 15 characters long")
private String password;
@ValidEmail
private String email;
@NotBlank
@Size(min=2, max=60)
private String name;
private boolean enabled = false;
private String authority;
// CONSTRUCTORS
public User() {
System.out.println("************* user created");
}
public User(String username, String password, boolean enabled, String authority, String email, String name) {
this.username = username;
this.password = password;
this.enabled = enabled;
this.authority = authority;
this.email = email;
this.name = name;
}
// GETTERS AND SETTERS
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((authority == null) ? 0 : authority.hashCode());
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result + (enabled ? 1231 : 1237);
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((username == null) ? 0 : username.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (authority == null) {
if (other.authority != null)
return false;
} else if (!authority.equals(other.authority))
return false;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
if (enabled != other.enabled)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (username == null) {
if (other.username != null)
return false;
} else if (!username.equals(other.username))
return false;
return true;
}
@Override
public String toString() {
return "User [username=" + username + ", email=" + email + ", name=" + name + ", enabled=" + enabled + ", authority=" + authority + "]";
}
}
Servlet XML配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="com.offers"></context:component-scan>
<context:annotation-config></context:annotation-config>
<mvc:annotation-driven></mvc:annotation-driven>
<mvc:resources location="/resources/" mapping="/static/**" />
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="com.offers.messages.messages"></property>
</bean>
<bean id="tilesViewResolver" class="org.springframework.web.servlet.view.tiles2.TilesViewResolver">
</bean>
<bean id="TilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/layouts/default.xml</value>
</list>
</property>
</bean>
</beans>
OffersService类
package com.offers.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.offers.dao.Offer;
import com.offers.dao.OfferDao;
@Service("offersService")
public class OffersService {
private OfferDao offerDao;
@Autowired
public void setOffersDao(OfferDao offersDao) {
this.offerDao = offersDao;
}
public List<Offer> getCurrent(){
return offerDao.getOffers();
}
public boolean create(Offer offer){
return offerDao.create(offer);
}
}
由于
答案 0 :(得分:0)
您正在获取NPE,因为您的对象默认为null
。
你甚至打电话给setters
注释的@Autowired
吗?
您可以自动将该字段自动装配
@Autowired
private OffersService offersService;
@Autowired
private OfferDao offerDao;