Spring-hibernate Data Insert - java

I'm trying to insert Data into table using HibernateTemplate but so far no luck.
here is code -
Catch
else
java.lang.NullPointerException
at com.imall.service.registrationService.regUser(registrationService.java:29)
at com.imall.web.LoginController.registerUser(LoginController.java:54)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doInvokeMethod(HandlerMethodInvoker.java:710)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:167)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:414)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:402)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:771)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:563)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1086)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:659)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1558)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1515)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
And Here is applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="dataSourceBean" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"> </property>
<property name="url" value="jdbc:mysql://localhost/test"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<bean id="sessionFactoryBean" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSourceBean"></property>
<property name="mappingResources">
<list>
<value>com/imall/pojo/User.hbm.xml</value>
<value>com/imall/pojo/regUser.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplateBean" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactoryBean"></property>
</bean>
<bean id="authenticateServiceBean" class="com.imall.service.AuthticateService">
<property name="hibernateTemplate" ref="hibernateTemplateBean"> </property>
</bean>
<bean id="registrationServiceBean" class="com.imall.service.registrationService">
<property name="hibernateTemplate" ref="hibernateTemplateBean"> </property>
</bean>
</beans>
Here is the Service Method-
public class registrationService {
private HibernateTemplate hibernateTemplate;
public registrationService()
{
}
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
public boolean regUser(com.imall.pojo.regUser rgUser)
{
System.out.println(rgUser.getfName());
try
{
System.out.println("in try--"+rgUser.getEmailId());
hibernateTemplate.save(rgUser);
return true;
}
catch(Exception e)
{
System.out.println("Catch");
e.printStackTrace();
return false;
}
}
Any help will be appreciated.
Here are the other code -
LoginController Method-
#Autowired
private registrationService regService;
#RequestMapping(value="/register.php",method = RequestMethod.POST)
public ModelAndView registerUser(#ModelAttribute("regDetails") regUser userReg)
{
System.out.println(userReg.getfName());
if(regService.regUser(userReg))
{
System.out.println("IF");
return new ModelAndView("success");
}
else
{
System.out.println("else");
return new ModelAndView("success");
}
}
The line 29 in RegistrationService is- hibernateTemplate.save(rgUser);
And this line System.out.println(rgUser.getfName()); is printing the name.

Related

Cannot invoke "" because "" is null

i finally find it question tab.
why this error is 'boom'?????
i didn't understand spend two days.....
**java.lang.NullPointerException: Cannot invoke
"com.board.dao.BoardDao.listboard(com.board.dto.BoardDto)" because "this.bDao" is null**
at com.board.service.BoardService.listboard(BoardService.java:19)
at com.board.controller.BoardController.boardlist(BoardController.java:25)
at com.board.controller.BoardController.boardlist(BoardController.java:26)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.base/java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:213)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:626)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:543)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:616)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:818)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1626)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Unknown Source)
controller
#Controller
public class BoardController {
#Autowired
BoardService service;
#RequestMapping("/board")
public ModelAndView boardlist (ModelAndView mv ,BoardDto dto) {
System.out.println("boardlist ");
System.out.println(dto+"dto");
List<BoardDto> dtolist = service.listboard(dto);
mv.addObject("boardlist", dtolist);
mv.setViewName("boardlist");
return mv;
}
}
controller is fine.. i think..
service
#Service
public class BoardService {
#Autowired
BoardDao bDao;
public List<BoardDto> listboard(BoardDto dto) {
System.out.println("boardservice");
List<BoardDto> result = bDao.listboard(dto);
return result ;
}
}
this position is error why?? T.T
i think this method is error position but i don't know understand. why???
dao
public class BoardDao extends SqlSessionDaoSupport{
#Autowired
SqlSessionTemplate session;
public List<BoardDto> listboard(BoardDto dto) {
System.out.println("dao.");
List<BoardDto> result = session.selectList("boarddate.listboard", dto);
return result;
}
}
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:#localhost:1521:orcl"/>
<property name="username" value="board"/>
<property name="password" value="1234"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- classpath: -> src/main/resources -->
<property name="configLocation" value="classpath:myBatis/myBatis-config.xml"/>
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
<!-- DI -->
<bean class="com.board.service.BoardService"></bean>
<bean class="com.board.dao.BoardDao">
<property name="sqlSessionTemplate" ref="sqlSession"/>
</bean>
</beans>
root-context.xml
why error is 'boom'? i didn't understand.... T.T
--> edit more infomation to error
I think your problem is related with the lack of a #Component annotation in your BoardDao class.
The component should have a #Component annotation to instantiate the singleton to be injected in your Service Layer.
#Component
public class BoardDao extends SqlSessionDaoSupport{
#Autowired
SqlSessionTemplate session;
public List<BoardDto> listboard(BoardDto dto) {
System.out.println("dao.");
List<BoardDto> result = session.selectList("boarddate.listboard", dto);
return result;
}
}
If the problem persist, you may try with the #Repository annotation. Sadly I haven't used the class SqlSessionDaoSupport, so I don't know exactly the best annotation for that.
In my case it was with a Map, I wanted to increase its value, but this initial one will not exist, therefore it is null.
map.put(0, map.get(0) 1);
It was fixed by adding a validation, like so:
map.put(0, map.get(0) != null ? map.get(0) + 1 : 1);

Issue Autowiring Bean in ItemProcessor

I have to autowire a service into my ItemProcessor to retrieve an object from the database and make some treatment but it's not working and I always gets java.lang.NullPointerException when trying to use it in my ItemProcessor.
Here is the context-model:
<import resource="classpath:context-datasource.xml"/>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>ma.controle.gestion.modele.Batch</value>
<value>ma.controle.gestion.modele.Ressource</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.enable_lazy_load_no_trans">true</prop>
</props>
</property>
</bean>
<!-- Transaction Manager is defined -->
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
Here is my process class
public class BatchItemProcessor implements ItemProcessor<Batch,Batch> {
#Autowired
#Qualifier("ressourceService")
private IRessourceService ressourceService;
// getters setters
#Override
public Batch process(Batch b) throws Exception {
return groupByTypeInstRub(batch);
}
public Batch groupByTypeInstRub(Batch b){
if(BatchFieldSetMapper.batchs.isEmpty()){
return null;
}else if(BatchFieldSetMapper.batchs.contains(b)){
Double montantPaye=0.0;
Double montantRetenu=0.0;
for (Iterator<Batch> iterator = BatchFieldSetMapper.batchs.iterator(); iterator.hasNext();) {
System.out.println("ressource Matricule : " + b.getMatricule());
Ressource ressource = (Ressource) ressourceService.findRessourceByMatricule(b.getMatricule());
System.out.println("Ressource nom, " + ressource.getNom() + ", Prenom : " + ressource.getPrenom());
Batch batch = (Batch) iterator.next();
if(b.getInstitution().equalsIgnoreCase(batch.getInstitution()) && b.getType().equals(batch.getType()) && b.getRubrique().equalsIgnoreCase(batch.getRubrique())){
montantPaye+=batch.getMontantPaye();
montantRetenu+=batch.getMontantRetenu();
iterator.remove();
}
}
b.setMontantPaye(montantPaye);
b.setMontantRetenu(montantRetenu);
return b;
}else
return null;
}
Here is my service
#Transactional
#Service("ressourceService")
public class RessourceServiceImpl implements IRessourceService {
#Autowired
#Qualifier("ressourceDao")
private RessourceDao ressourceDao;
#Override
public Ressource findRessourceByMatricule(String matricule) {
System.out.println("Find ressource By Matricule, Dao");
return ressourceDao.findRessourceByMatricule(matricule);
}
// getters setters
}
and here is my ressourceDao
#Repository
public class RessourceDao extends GenericDaoHibernateImpl{
#Autowired
#Qualifier("sessionFactory")
private SessionFactory sessionFactory;
#Autowired
public RessourceDao(#Qualifier("sessionFactory") SessionFactory sessionFactory){
super(sessionFactory);
}
public Ressource findRessourceByMatricule(String matricule){
System.out.println("Find ressource By Matricule, Dao");
Ressource ressource=null;
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Ressource.class);
criteria.add(Restrictions.eq("matricule",matricule));
List<Ressource> ressources = criteria.list();
for (Ressource ressource2 : ressources) {
System.out.println("ressource nom, prenom " + ressource2.getNom() + "," + ressource2.getPrenom());
}
if(ressources.equals(null)){
return null;
}else{
ressource=ressources.get(0);
}
return ressource;
}
}
and here is the log of the error
java.lang.NullPointerException
at ma.controle.gestion.springbatch.BatchItemProcessor.groupByTypeInstRub(BatchItemProcessor.java:43)
at ma.controle.gestion.springbatch.BatchItemProcessor.process(BatchItemProcessor.java:30)
at ma.controle.gestion.springbatch.BatchItemProcessor.process(BatchItemProcessor.java:1)
at org.springframework.batch.core.step.item.SimpleChunkProcessor.doProcess(SimpleChunkProcessor.java:125)
at org.springframework.batch.core.step.item.SimpleChunkProcessor.transform(SimpleChunkProcessor.java:291)
at org.springframework.batch.core.step.item.SimpleChunkProcessor.process(SimpleChunkProcessor.java:190)
at org.springframework.batch.core.step.item.ChunkOrientedTasklet.execute(ChunkOrientedTasklet.java:74)
at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:386)
at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:130)
at org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext(TaskletStep.java:264)
at org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration(StepContextRepeatCallback.java:76)
at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:367)
at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:214)
at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:143)
at org.springframework.batch.core.step.tasklet.TaskletStep.doExecute(TaskletStep.java:250)
at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:195)
at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:135)
at org.springframework.batch.core.job.flow.JobFlowExecutor.executeStep(JobFlowExecutor.java:61)
at org.springframework.batch.core.job.flow.support.state.StepState.handle(StepState.java:60)
at org.springframework.batch.core.job.flow.support.SimpleFlow.resume(SimpleFlow.java:144)
at org.springframework.batch.core.job.flow.support.SimpleFlow.start(SimpleFlow.java:124)
at org.springframework.batch.core.job.flow.FlowJob.doExecute(FlowJob.java:135)
at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:293)
at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:120)
at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:48)
at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:114)
at ma.controle.gestion.bean.batch.BatchExcelBean.uploadFile(BatchExcelBean.java:82)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.el.parser.AstValue.invoke(AstValue.java:279)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:273)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at org.primefaces.component.fileupload.FileUpload.broadcast(FileUpload.java:319)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:755)
at javax.faces.component.UIViewRoot.processDecodes(UIViewRoot.java:931)
at com.sun.faces.lifecycle.ApplyRequestValuesPhase.execute(ApplyRequestValuesPhase.java:78)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.primefaces.barcelona.filter.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:32)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:958)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1087)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
I have another configuration applicationContext in web-inf But when I run the batch I access this configuration which are in resources class path.

redis.clients.jedis.exceptions.JedisException: Could not get a resource from the pool

redis.properties
#jedisPoolConfig
redis.minIdle=100
redis.maxIdle=500
redis.maxTotal=50000
redis.maxWaitMillis=10000
redis.testOnBorrow=true
#jedisPool
redis.host=192.168.13.169
redis.port=6379
redis.timeout=3000
redis.port2=6380
#redis-sentinel
redis.sentinel=192.168.13.169:26379
redis.master=mymaster
spring-redis.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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--properties配置-->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:redis.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>
<!-- 连接池配置信息 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxTotal" value="${redis.maxTotal}" />
<property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
</bean>
<!--初级版:单实例-->
<bean id="jedisPool" class="redis.clients.jedis.JedisPool" scope="singleton">
<constructor-arg name="poolConfig" ref="jedisPoolConfig" />
<constructor-arg name="host" value="${redis.host}" />
<constructor-arg name="port" value="${redis.port}" type="int" />
</bean>
<!--主从-->
<bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool">
<constructor-arg index="0" ref="jedisPoolConfig" />
<constructor-arg index="1">
<list>
<bean class="redis.clients.jedis.JedisShardInfo">
<constructor-arg name="host" value="${redis.host}" />
<constructor-arg name="port" value="${redis.port}" />
<constructor-arg name="timeout" value="${redis.timeout}" />
<constructor-arg name="name" value="master" />
</bean>
<bean class="redis.clients.jedis.JedisShardInfo">
<constructor-arg name="host" value="${redis.host}" />
<constructor-arg name="port" value="${redis.port2}" />
<constructor-arg name="timeout" value="${redis.timeout}" />
<constructor-arg name="name" value="slave1" />
</bean>
</list>
</constructor-arg>
</bean>
<!--sentinel模式-->
<bean id="redisSentinelConfiguration" class="org.springframework.data.redis.connection.RedisSentinelConfiguration">
<constructor-arg name="master" value="${redis.master}" />
<constructor-arg name="sentinelHostAndPorts">
<set>
<value>${redis.sentinel}</value>
</set>
</constructor-arg>
</bean>
<!--Jedis连接池-->
<bean id="jedisConnFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:use-pool="true">
<property name="hostName" value="${redis.host}"/>
<constructor-arg ref="redisSentinelConfiguration" />
<constructor-arg ref="jedisPoolConfig" />
</bean>
<!-- redis template definition -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate" p:connection-factory-ref="jedisConnFactory"/>
<bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
Code
Controller
#Controller
public class JedisController {
......
#Autowired
private RedisService redisService;
#RequestMapping(value = "test2")
#ResponseBody
public String test2(){
redisService.set("key2","v2");
return redisService.get("key1");
}
......
}
Service
#Service
public class RedisService extends BinaryRedisService {
public RedisService() {}
public String set(final String key, final String value) {
return (String)this.execute(new Function<ShardedJedis, String>() {
public String callBack(ShardedJedis shardedJedis) {
return shardedJedis.set(key, value);
}
});
}
......
}
public class BinaryRedisService {
#Autowired
protected ShardedJedisPool shardedJedisPool;
public BinaryRedisService() {
}
protected <T> T execute(Function<ShardedJedis, T> fun) {
ShardedJedis shardedJedis = null;
T t = null;
try {
shardedJedis = this.shardedJedisPool.getResource();
t = fun.callBack(shardedJedis);
} catch (Exception var8) {
var8.printStackTrace();
} finally {
if(null != shardedJedis) {
shardedJedis.close();
}
return t;
}
}
......
}
Problem
redis.clients.jedis.exceptions.JedisException: Could not get a
resource from the pool at
redis.clients.util.Pool.getResource(Pool.java:51) at
redis.clients.jedis.ShardedJedisPool.getResource(ShardedJedisPool.java:36)
at
org.henry.service.BinaryRedisService.execute(BinaryRedisService.java:29)
at org.henry.service.RedisService.set(RedisService.java:25) at
org.henry.service.RedisService$$FastClassBySpringCGLIB$$f57afd3.invoke()
at
org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at
org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:721)
at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at
org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
at
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at
org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at
org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:656)
at
org.henry.service.RedisService$$EnhancerBySpringCGLIB$$d4e52321.set()
at
org.henry.controller.JedisController.test2(JedisController.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497) at
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687) at
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) at
org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:837)
at
org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:583)
at
org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
at
org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:548)
at
org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:226)
at
org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1180)
at
org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:511)
at
org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
at
org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1112)
at
org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at
org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:213)
at
org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:119)
at
org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)
at org.eclipse.jetty.server.Server.handle(Server.java:524) at
org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:319) at
org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:253)
at
org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:273)
at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95)
at
org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:93)
at
org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.executeProduceConsume(ExecuteProduceConsume.java:303)
at
org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceConsume(ExecuteProduceConsume.java:148)
at
org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:136)
at
org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671)
at
org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589)
at java.lang.Thread.run(Thread.java:745) Caused by:
java.util.NoSuchElementException: Unable to validate object at
org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:506)
at
org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:363)
at redis.clients.util.Pool.getResource(Pool.java:49) ... 58 more
You need to make sure that a) Redis is running b) that it is able to accept connections from remote hosts and c) if you have enabled password protection, provide a password in your code.
To make sure that it can accept connections from remote hosts you have to look at the redis.conf file. Find the line with the binding addresses (it should look something like: bind 127.0.0.1) and either comment it out (so it can accept requests from all remote hosts - not recommended for production, but it's OK for testing), or add the remote IPs you want your Redis service to accept connections from.

Spring Hibernate - NullPointerException SessionFactory

I got an error about SessionFactory.
CrudController.java
#Controller
public class CrudController {
#Autowired
private AlbumBo albumBo;
#RequestMapping(value = "/addAlbum")
#ResponseBody
public void addAlbum(
#RequestParam("NameRecordCompany") String nameRecordCompany,
#RequestParam("NameAlbum") String nameAlbum,
#RequestParam("YearName") String yearAlbum,
#RequestParam("NameArtist") String nameArtist,
#RequestParam("NameCategory") String nameCategory,
#RequestParam("SongList") String songList) throws JSONException {
Song temp = new Song();
ArrayList<Song> listaCanzoni = new ArrayList();
String songs = "{" + "\"songs\":" + songList + "}";
JSONObject jsonObjectSongList = new JSONObject(songs);
JSONArray jsonArraySongList = (JSONArray) jsonObjectSongList.get("songs");
for (int i = 0; i < jsonArraySongList.length(); i++) {
temp.setName((String) jsonArraySongList.getJSONObject(i).get("songName"));
temp.setDuration((String) jsonArraySongList.getJSONObject(i).get("songDuration"));
listaCanzoni.add(new Song(temp.getName(), temp.getDuration()));
}
Artist artist = new Artist(nameArtist);
Category category = new Category(nameCategory);
Album album = new Album(nameAlbum, yearAlbum);
album.setArtist(artist);
album.setCategory(category);
try {
albumBo.save(album); //line 67
JOptionPane.showMessageDialog(null, "albumDao.save(album) eseguita");
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
AlbumDaoImpl.java
public class AlbumDaoImpl implements AlbumDao {
#Autowired
SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory factory) {
this.sessionFactory = factory;
}
#Override
public void save(Album album) throws Exception {
Session session = sessionFactory.openSession(); //line 38
Transaction tx = null;
try {
tx = session.beginTransaction();
session.saveOrUpdate(album);
tx.commit();
} catch (HibernateException e) {
if (tx != null) {
tx.rollback();
} else {
e.printStackTrace();
}
} finally {
session.close();
}
}
}
AlbumBoImpl.java
public class AlbumBoImpl implements AlbumBo{
private AlbumDao albumDao;
static final Logger logger = Logger.getLogger(AlbumBoImpl.class);
public AlbumDao getAlbumDao() {
return albumDao;
}
public void setAlbumDao(AlbumDao albumDao) {
this.albumDao = albumDao;
}
#Override
public void save(Album album) throws Exception {
try{
albumDao.save(album); //line 35
}catch(Exception e){
logger.error(e);
throw e;
}
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}"/>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>it.davidefruci.casadiscografica2.beans.Album</value>
<value>it.davidefruci.casadiscografica2.beans.Artist</value>
<value>it.davidefruci.casadiscografica2.beans.Song</value>
<value>it.davidefruci.casadiscografica2.beans.RecordCompany</value>
<value>it.davidefruci.casadiscografica2.beans.Category</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="dataSource" ref="dataSource" />
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- DAO -->
<bean id="albumDao" class="it.davidefruci.casadiscografica2.daoImpl.AlbumDaoImpl"/>
<bean id="artistDao" class="it.davidefruci.casadiscografica2.daoImpl.ArtistDaoImpl"/>
<bean id="categoryDao" class="it.davidefruci.casadiscografica2.daoImpl.CategoryDaoImpl"/>
<bean id="recordCompanyDao" class="it.davidefruci.casadiscografica2.daoImpl.RecordCompanyDaoImpl"/>
<bean id="songDao" class="it.davidefruci.casadiscografica2.daoImpl.SongDaoImpl"/>
<!-- BO -->
<bean id="albumBo" class="it.davidefruci.casadiscografica2.boImpl.AlbumBoImpl">
<property name="albumDao" ref="albumDao"></property>
</bean>
<bean id="artistBo" class="it.davidefruci.casadiscografica2.boImpl.ArtistBoImpl">
<property name="artistDao" ref="artistDao"></property>
</bean>
<bean id="categoryBo" class="it.davidefruci.casadiscografica2.boImpl.CategoryBoImpl">
<property name="categoryDao" ref="categoryDao"></property>
</bean>
<bean id="recordCompanyBo" class="it.davidefruci.casadiscografica2.boImpl.RecordCompanyBoImpl">
<property name="recordCompanyDao" ref="recordCompanyDao"></property>
</bean>
<bean id="songBo" class="it.davidefruci.casadiscografica2.boImpl.SongBoImpl">
<property name="songDao" ref="songDao"></property>
</bean>
I have a JSP where I add the datas that I want to save into my db.
When I click on the submit button, an Ajax call is invoked. This call invokes the CrudController, who should save data on my db with addAlbum method.
When the CrudController is invoked Tomcat tells me:
java.lang.NullPointerException
at it.davidefruci.casadiscografica2.daoImpl.AlbumDaoImpl.save(AlbumDaoImpl.java:38)
at it.davidefruci.casadiscografica2.boImpl.AlbumBoImpl.save(AlbumBoImpl.java:35)
at it.davidefruci.casadiscografica2.controllers.CrudController.addAlbum(CrudController.java:67)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:777)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:706)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1521)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1478)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
I wrong something with the sessionFactory initialization?
<bean id="personDao"class="com.studytrails.tutorials.springhibernatesessionfactory.PersonDao">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
You will need to inject session factory in DAO you are using which will help you do CRUD operations on your Object either you can configure this in XML or using annotation.
Also please help your self by going through the given like below
Example of spring hibernate integration
Two things you can do, one is change to inject the SessionFactory to Dao by yourself.
<!-- DAO -->
<bean id="albumDao" class="it.davidefruci.casadiscografica2.daoImpl.AlbumDaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
You can do this for all DAOs.
Or
put a component scan on the applicationContext.xml XML configuration so that the SessionFactory will get Autowired.
<context:component-scan base-package="it.davidefruci.casadiscografica2"/>

Spring. AutoWired object NullPointerException [duplicate]

This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Closed 9 years ago.
I have two classes.
CustomUserDetailsService - Works fine!
#Service
#Transactional(readOnly = true)
#SuppressWarnings("unused")
public class CustomUserDetailsService implements UserDetailsService {
#Autowired
private UserDAO userDAO;
#Override
public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
return userDAO.getUser(login);
}
public UserDAO getUserDAO() {
return userDAO;
}
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
}
RegistrationServiceImpl - Throws NullPointerException on userDAO.addUser(newUser); method call.
#Service
#Transactional(readOnly = false)
public class RegistrationServiceImpl implements RegistrationService {
#Autowired
private UserDAO userDAO;
#Override
public void registerUser(Registration reg) {
User newUser = new User();
newUser.setUsername(reg.getUsername());
newUser.setPassword(reg.getPassword());
newUser.setFirstName(reg.getFirstName());
newUser.setLastName(reg.getLastName());
userDAO.addUser(newUser);
}
public UserDAO getUserDAO() {
return userDAO;
}
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
}
mvc-dispatcher-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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.petrez" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/Library" />
<property name="username" value="root" />
<property name="password" value="G190419g" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="packagesToScan" value="com.petrez" />
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="show_sql">false</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.petrez.model.User</value>
<value>com.petrez.model.Role</value>
</list>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="userDAO" class="com.petrez.dao.UserDAOImpl" />
<bean id="roleDAO" class="com.petrez.dao.RoleDAOImpl" />
<bean id="userDetailsService" class="com.petrez.service.CustomUserDetailsService" />
<bean id="registrationService" class="com.petrez.service.RegistrationServiceImpl" />
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
Can anyone say me, why?
Thanks!
UPD
Stack Trace:
Nov 08, 2013 11:04:33 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [mvc-dispatcher] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at com.petrez.service.RegistrationServiceImpl.registerUser(RegistrationServiceImpl.java:28)
at com.petrez.controller.RegistrationPage.processRegistration(RegistrationPage.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:440)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:428)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:183)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:343)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:260)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)
RegistrationPage
#Controller
#RequestMapping(value = "/registration")
#SuppressWarnings("unused")
public class RegistrationPage {
#RequestMapping(method = RequestMethod.POST)
public String processRegistration(#ModelAttribute("reg") Registration reg, BindingResult result) {
if(result.hasErrors()) {
return "/?error=true";
}
else {
new RegistrationServiceImpl().registerUser(reg);
return "success-login";
}
}
}
You're manually instantiating the RegistrationServiceImpl instead of retrieving the Spring-managed bean from the context. Inject the RegistrationService into your RegistrationPage.
You missed <context:annotation-config/> in your configuration
Add <context:annotation-config/> or <context:component-scan base-package="org.example"/>
to top of your mvc-dispatcher-servlet.xml configuration file.
eg
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:component-scan base-package="org.example"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp" />
</bean>
</beans>

Categories