它是第一次将spring与hibernate整合在一起,当我 调用Dao类的任何方法我得到空指针异常
我正在使用抽象工厂模式Abstract class的源代码:
public abstract class Content {
@Autowired
HibernateOperations ho;
@Transactional
public List<ContentDes> getContentDes(String sql,int limit){
//do it with autowired
List<Object[]> ls = new ArrayList<Object[]>();
List<ContentDes> contentDes_ls = new ArrayList<ContentDes>();
System.out.println("--before invoking method---");
ho.just_print();
ls = ho.getResultListByLimit(sql,limit);
for(Object[] obj: ls){
ContentDes contentDes = new ContentDes();
contentDes.setCode((String)obj[0]);
contentDes.setContent_prv((String)obj[1]);
contentDes.setPricetag((String)obj[2]);
contentDes_ls.add(contentDes);
}
return contentDes_ls;
}
abstract List<ContentDes> getRandomContent(int limit);
//abstract List<ContentDes> getDistinctCat();
}
我有五个课程正在扩展我的内容类:编码 我的一个孩子在下面说谎:
public class Wallpaper extends Content{
@Override
public List<ContentDes> getRandomContent(int limit) {
String sql = "select code,prv,pricetag from Wallpaper where cat not like 'Holy Deities' order by rand() limit "+limit+"";
List<ContentDes> contentDes_ls = new ArrayList<ContentDes>();
contentDes_ls = getContentDes(sql,limit);
return contentDes_ls;
}
}
返回clasess的类根据内容类型进行观察 是:
public class GetContentFactory {
//use getContent method to get object of type Content
public Content getContent(String contentType) {
contentType = contentType.toLowerCase();
if (contentType.equalsIgnoreCase("wallpaper")) {
return new Wallpaper();
} else if (contentType.equalsIgnoreCase("animation")) {
return new Animation();
} else if (contentType.equalsIgnoreCase("ringtone")) {
return new Ringtone();
} else if (contentType.equalsIgnoreCase("video")) {
return new Video();
}
else if (contentType.equalsIgnoreCase("game")) {
return new Game();
}
else {
System.out.println(" unknow request in GetContentFactory class");
}
return null;
}
}//end of GetContentFactory class.
我的主要课程是:
public class GetContent {
GetContentFactory contentFactory = new GetContentFactory();
}
public List<ContentDes> getRandomContent(String content_type, int limit) {
List<ContentDes> contentDes_ls = new ArrayList<ContentDes>();
Content con = contentFactory.getContent(content_type);
contentDes_ls = con.getRandomContent(limit);
for (ContentDes contentDes : contentDes_ls) {
System.out.println("prv----"+contentDes.getContent_prv());
}
return contentDes_ls;
}
}
我的dao类的代码是:
@Repository
public class HibernateOperations {
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
//pass the sql query to get result for multiple column
public List<Object[]> getResultListByLimit(String query,int limit){
System.out.println("in get result-------");
Session session = this.sessionFactory.getCurrentSession();
List<Object[]> ls_ob = new ArrayList<Object[]>();
Query q = session.createQuery(query);
q.setMaxResults(limit);
ls_ob = (List<Object[]>)q.list();
return ls_ob;
}
public List<Object> getListForSingleColumn(String query){
Session session = this.sessionFactory.getCurrentSession();
List<Object> ls_ob = new ArrayList<Object>();
Query q = session.createQuery(query);
ls_ob = q.list();
return ls_ob;
}
public void SaveObject(Object obj){
Session session = this.sessionFactory.getCurrentSession();
List<Object[]> ls_ob = new ArrayList<Object[]>();
session.save(obj);
}
public void just_print(){
System.out.println("---------in method hibenate operation------");
}
}
当我的控制器类方法调用时:
GetContent gc = new GetContent();
List<ContentDes> contentDes_ls = new ArrayList<ContentDes>(); contentDes_ls = gc.getRandomContent("wallpaper", 3);
我有一个例外:
打印
--before invoking method---(its is the sout of my content class method Name "getContentDes")
Apr 25, 2016 6:03:04 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [DefaultServlet] in context with path [/slwap_sh] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at lanka.content.get.Content.getContentDes(Content.java:37)
at lanka.content.get.Wallpaper.getRandomContent(Wallpaper.java:45)
at lanka.content.controller.ContentController.sriWap(ContentController.java:65)
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.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)
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.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:860)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
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:212)
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:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
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:1096)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
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)
我无法调用任何我的Dao类方法,我得到了空指针 当我调用我的Dao(HibernateOperations.java)类
的任何方法时任何人都可以帮我找出我的错误
DefaultServlet-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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<mvc:annotation-driven />
<mvc:annotation-driven enable-matrix-variables="true" />
<context:component-scan base-package="lanka.content.controller" />
<context:component-scan base-package="lanka.content.domain" />
<context:component-scan base-package="lanka.content.utility" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- start of languages xml code -->
<!-- lang param is defined in the mvc interceptor -->
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="WEB-INF/propFiles/content" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="en" />
</bean>
<!-- end of languages xml code -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
</mvc:interceptor>
<!-- <mvc:interceptor>
<mvc:mapping path="/**" />
<mvc:exclude-mapping path="/resources/**"/>
<bean id="storingWapHits"
class="vodafone.interceptor.StroringHits">
</bean>
</mvc:interceptor> -->
</mvc:interceptors>
<mvc:resources mapping="/resources/**" location="/resources/design/" />
<!-- start of hibernate integration -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/wapsite" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<!-- hibernate4AnnotatedSessionFactory is a session fectory-->
<!-- Hibernate 4 SessionFactory Bean definition -->
<bean id="hibernate4AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>lanka.content.table.Game</value>
<value>lanka.content.table.Scrsaver</value>
<value>lanka.content.table.Video</value>
<value>lanka.content.table.Wallpaper</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</bean>
<!-- <bean id="personService" class="com.journaldev.spring.service.PersonServiceImpl">
<property name="personDAO" ref="personDAO"></property>
</bean>-->
<bean id="HibernateOperations" class="lanka.content.utility.HibernateOperations">
<property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</bean>
</beans>
答案 0 :(得分:1)
通过做:
new Wallpaper();
你不是让春天做他的工作,也就是说在你的物体中注入东西:
@Autowired
HibernateOperations ho;
ho
将始终为null。
每个Content
子类都应该是spring bean,你必须摆脱你的GetContentFactory
,并且只对每一个spring bean自动装配
编辑:抽象工厂设计
像这样定义你的bean:
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class Wallpaper extends Content {
将GetContentFactory
声明为弹簧bean:
@Component
public class GetContentFactory {
@Autowired
private Wallpaper wallpaper;
这也必须避免:
GetContentFactory contentFactory = new GetContentFactory();