Servlet @Autowired Spring Bean 的方法 .
2014-05-13 21:53
393 查看
使用@Autowired自动装配Bean时出现错误,代码如下:
代码getDataForWebService.getYJGNQ()会java.lang.NullPointerException,因为getDataForWebService 没有装配上,所以是空指针
解决方式如下:
第一种:
在Servlet的init方法中增加以下代码,即可通知Servlet在启动时,自动查找getDataForWebService并装配,
这个在配置文件中配置好使,但现在我们使用的自动装配,那就要用第二种。
第二种方式:
原文:点击打开链接
public class GetYJGNQ extends HttpServlet { @Autowired private IDataForWebService getDataForWebService; /** * */ private static final long serialVersionUID = 1L; public void setGetDataForWebService(IDataForWebService getDataForWebService) { this.getDataForWebService = getDataForWebService; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.print(getDataForWebService.getYJGNQ()); out.flush(); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
代码getDataForWebService.getYJGNQ()会java.lang.NullPointerException,因为getDataForWebService 没有装配上,所以是空指针
解决方式如下:
第一种:
在Servlet的init方法中增加以下代码,即可通知Servlet在启动时,自动查找getDataForWebService并装配,
public void init(ServletConfig config) throws ServletException { ServletContext servletContext = config.getServletContext(); WebApplicationContext webApplicationContext = WebApplicationContextUtils .getWebApplicationContext(servletContext); AutowireCapableBeanFactory autowireCapableBeanFactory = webApplicationContext .getAutowireCapableBeanFactory(); autowireCapableBeanFactory.configureBean(this, "getDataForWebService"); }
这个在配置文件中配置好使,但现在我们使用的自动装配,那就要用第二种。
第二种方式:
public void init(ServletConfig config) throws ServletException { SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext()); }
原文:点击打开链接
相关文章推荐
- servlet中无法直接autowired bean from Spring
- servlet中利用spring的注解@Autowired自动注入service失败,优雅的解决方法
- Spring @Controller 中@RequestMapping()注解private方法无法访问到@Autowired的bean
- Servlet中使用Spring的@Autowired程序报nullexception
- 注解的力量 -----Spring 2.5 JPA hibernate 使用方法的点滴整理(三):通过 @Autowired的使用来消除 set ,get方法。
- Spring使用@Autowired,@Qualifier,@Resource注解配置bean
- Spring Boot异常:BeanCreationException:Injection of autowired dependencies failed;
- Spring学习笔记十一---Bean之间的关系@Autowired
- servlet中注入spring托管bean的方法
- Spring @Autowired注解私有属性(无set方法,无构造方法可以access此私有属性)
- Spring in action 01 -- 装配 Bean(@Autowired)
- spring 使用annotation 自动注册bean,并保证@Required,@Autowired的属性被注入
- 【Spring学习笔记-6】关于@Autowired与@Scope(BeanDefination.SCOPE_PROTOTYPE)
- 通过 @Autowired的使用来消除 set ,get方法 ---- Spring · JPA ·hibernate 的使用方法
- Spring 通过Autowired 和 Context.getBean()方式拿到的不是同一个Bean
- 在工具类静态方法调用@Autowired注入的bean方法
- spring问题:Error creating bean with name 'articleController': Injection of autowired dependencies fail
- new 出的对象,无法调用@Autowired进入的spring bean
- 为什么servlet中无法直接autowired bean from applicationC...
- Spring @Autowired注解私有属性(无set方法)