首页 > 其他分享 >自定义标签中 如何使用 Spring 的 ioc

自定义标签中 如何使用 Spring 的 ioc

时间:2023-02-19 11:01:05浏览次数:37  
标签:WebApplicationContext 自定义 getInstance Spring AppContext servletContext 标签 ioc


自定义标签,继承了BodyTagSupport

 

在标签类上加了@Component,还是无法使用 IOC,不知道为啥。

 

@Autowired
private ForumPostsMng forumPostsMng;

 调用forumPosts时,抛空异常

 

但可以这样使用:

ApplicationContext applicationContext = AppContext.getInstance().getApplicationContext();
ForumModeratorMng forumModeratorMng = (ForumModeratorMng)applicationContext.getBean("forumModeratorMngImpl");

 

 在某个Servlet的init方法中,把WebApplicationContext获取后放入静态类AppContext中

public void init(ServletConfig config) throws ServletException {
ServletContext servletContext = config.getServletContext();
AppContext.getInstance().setServletContext(servletContext);

WebApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
AppContext.getInstance().setApplicationContext(appContext);

}

 然后,让Servlet随容器启动

 


<servlet>
<servlet-name>AppContextServlet</servlet-name>
<servlet-class>com.club.community.servlet.AppContextServlet</servlet-class>
<init-param>
<param-name>shutdown-on-unload</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>50</load-on-startup>
</servlet>


标签:WebApplicationContext,自定义,getInstance,Spring,AppContext,servletContext,标签,ioc
From: https://blog.51cto.com/u_21817/6066631

相关文章