WEB Spring getBean NULL
web.xml
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframeswork.org/dtd/spring-beans.dtd">
<beans>
<bean id="sumbean" class="mytest.Test"></bean>
</beans>
Servlet
http://localhost:8080/OrderTickets/servlet/SpringTestServlet?a=1&b=2
java.lang.NullPointerException
at mytest.SpringTestServlet.service(SpringTestServlet.java:36)
Test t = (Test)ctx.getBean("sumBean");//36行
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/beans.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoader</listener-class>
</listener>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>SpringTestServlet</servlet-name>
<servlet-class>mytest.SpringTestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SpringTestServlet</servlet-name>
<url-pattern>/servlet/SpringTestServlet</url-pattern>
</servlet-mapping>
</web-app>beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframeswork.org/dtd/spring-beans.dtd">
<beans>
<bean id="sumbean" class="mytest.Test"></bean>
</beans>
Servlet
public class SpringTestServlet extends HttpServlet {
public void service(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException{
ServletContext sc= getServletContext();
WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(sc);
PrintWriter out = response.getWriter();
int a = Integer.valueOf(request.getParameter("a"));
out.print(a);
out.print("+");
int b = Integer.valueOf(request.getParameter("a"));
out.print(b);
out.print("=");
Test t = (Test)ctx.getBean("sumBean");
out.print(t.sum(a,b));
}
}
public class Test {
public int sum(int x,int y){
return x+y;
}
}http://localhost:8080/OrderTickets/servlet/SpringTestServlet?a=1&b=2
java.lang.NullPointerException
at mytest.SpringTestServlet.service(SpringTestServlet.java:36)
Test t = (Test)ctx.getBean("sumBean");//36行
...全文
相关推荐
Java类获取Spring中bean的5种方式
主要为大家详细介绍了Java类获取Spring中bean的5种方式,感兴趣的小伙伴们可以参考一下
Spring通过ApplicationContext主动获取bean的方法讲解
今天小编就为大家分享一篇关于Spring通过ApplicationContext主动获取bean的方法讲解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
Spring获取webapplicationcontext,applicationcontext几种方法详解
Spring获取webapplicationcontext,applicationcontext几种方法详解
解析Java中如何获取Spring中配置的bean
本篇文章是对在Java中如何获取Spring中配置的bean进行了详细的分析介绍,需要的朋友参考下
java定时任务代码-spring管理.txt
java定时任务代码-spring管理.txtjava定时任务代码-spring管理.txtjava定时任务代码-spring管理.txt


Web 开发
