Java 尝试在SpringMVC控制器中使用entityManager时出现NullPointerException
我现在正在学习SpringMVC,并尝试创建简单的登录表单。 当执行entityManager.createQuery()方法时,我得到了NullPointerException。 我真的试过定义Java 尝试在SpringMVC控制器中使用entityManager时出现NullPointerException,java,spring,spring-mvc,Java,Spring,Spring Mvc,我现在正在学习SpringMVC,并尝试创建简单的登录表单。 当执行entityManager.createQuery()方法时,我得到了NullPointerException。 我真的试过定义 ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); LoginController loginController =
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
LoginController loginController = (LoginController) context.getBean("loginController");
loginController.userService.validate(username,password);
它工作正常,但是我可以在不定义上下文和初始化loginController的情况下使用我的userService吗
我的LoginController完整代码:
@Controller
public class LoginController
{
private UserService userService;
@RequestMapping("/")
public ModelAndView login()
{
ModelAndView mav = new ModelAndView("login");
return mav;
}
@RequestMapping("/validateLogin")
public ModelAndView validateLogin(HttpServletResponse response, HttpServletRequest request)
{
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
LoginController loginController = (LoginController) context.getBean("loginController");
String username = request.getParameter("username");
String password = request.getParameter("password");
ModelAndView mav = new ModelAndView("login");
if(!loginController.userService.validate(username,password))
{
String message = "Invalid credentials";
mav.addObject("errorMessage", message);
}
else
{
try
{
response.sendRedirect("/welcome");
}
catch (IOException e)
{
e.printStackTrace();
}
}
return mav;
}
public void setUserService(UserService userService)
{
this.userService = userService;
}
}
Mu用户服务代码:
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;
public class UserService
{
@PersistenceContext
private EntityManager entityManager;
public boolean validate(String username, String password)
{
boolean isValid = false;
Query query = entityManager.createQuery("from User where username = :user and password = :pass");
query.setParameter("user",username);
query.setParameter("pass",password);
List result = query.getResultList();
if(!result.isEmpty())
{
isValid = true;
}
return isValid;
}
}
我的应用程序上下文:
<?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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="ua.dp.advertParser"/>
<context:annotation-config></context:annotation-config>
<context:property-placeholder location="classpath:persistence.properties" />
<bean id="user" class="ua.dp.advertParser.dao.entity.User" lazy-init="true"/>
<bean id="userService" class="ua.dp.advertParser.core.UserService" lazy-init="true">
</bean>
<bean id="loginController" class="ua.dp.advertParser.controllers.LoginController">
<property name="userService" ref="userService"/>
</bean>
<bean id="registerController" class="ua.dp.advertParser.controllers.RegisterController">
<property name="userService" ref="userService"/>
</bean>
<!-- JPA & Hibernate configs -->
<bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="ua.dp.advertParser" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
</props>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.user}" />
<property name="password" value="${jdbc.pass}" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="myEmf" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
您没有自动连接您的用户服务 在用户服务上方放置
@Autowired
注释:
@Autowired
private UserService userService;
你也可以自动连线你的设定器
@Autwore
public void setUserService(UserService userService)
{
this.userService = userService;
}
另外,如果将UserService
类标记为@Service
,则只要要扫描的包包含服务所在的包,就不需要将其放入xml类中
这将使spring正确初始化用户服务bean
您没有自动连接用户服务 在用户服务上方放置
@Autowired
注释:
@Autowired
private UserService userService;
你也可以自动连线你的设定器
@Autwore
public void setUserService(UserService userService)
{
this.userService = userService;
}
另外,如果将UserService
类标记为@Service
,则只要要扫描的包包含服务所在的包,就不需要将其放入xml类中
这将使spring正确初始化用户服务bean
那么您在此处发布的代码有效吗?你想知道你是否需要做一个loginController来获得用户服务?您是否尝试过context.getBean(“userService”)@MarkD是的,如果我只获得userService,它也可以工作。我可以通过配置上下文或注释来避免任何bean初始化吗?那么您在这里发布的代码可以工作吗?你想知道你是否需要做一个loginController来获得用户服务?您是否尝试过context.getBean(“userService”)@MarkD Yes,如果我只获得userService,它也可以工作。我可以通过配置上下文或注释避免任何bean初始化吗?最好将其作为构造函数参数注入,因为它是一个必需的依赖项。我正试图按照您的建议来做,但现在它返回了新的异常:通过字段“userService”表示的未满足的依赖项Chrylis声明它是一个必需的依赖项,所以您可以自动连接setter而不是实际的字段。这应该会清除你的异常。请参阅我的编辑。最好将其作为构造函数参数注入,因为它是必需的依赖项。我正试图按照您的建议进行操作,但现在它返回了新的异常:通过字段“userService”Chrylis表示的未满足的依赖项声明了它是必需的依赖项,因此您可以自动关联setter,而不是实际的字段。这应该会清除你的异常。请参阅我的编辑。