日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

自定义注解的spring注入问题

發布時間:2023/12/31 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 自定义注解的spring注入问题 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

2019獨角獸企業重金招聘Python工程師標準>>>

? ?我就我遇到的自定義注解無法注入的問題整理一下:

1、遇到的問題

? ? SpringMvc的注入式通過id去查找上下文,這種方式用起來非常好用,但是在使用自定義標簽時遇到了問題,注入永遠為空。這是為什么呢?

? ? 這是因為spring 注解注入@Autowired?前提是這個類被實例化,你自定義的標簽只有在調用的時候?才會實例化的。

2、解決辦法

?1、?如果使用 Spring 的 MVC 包,則可以使用 RequestContextAwareTag 類。例:

public class AuthTag extends RequestContextAwareTag {private IAuthService authService;private String auth;public String getAuth() {return auth;}public void setAuth(String auth) {this.auth = auth;}@Overrideprotected int doStartTagInternal() throws Exception {boolean result = false;String erp = LoginContext.getLoginContext().getPin();authService = (IAuthService) this.getRequestContext().getWebApplicationContext().getBean("authService");List<SysAuth> list = authService.getByErp(erp);for(SysAuth a:list){if(auth.equals(a.getToken())){result = true;}}return result? EVAL_BODY_INCLUDE : SKIP_BODY;} }

2、沒有使用Spring的Mvc包則建議使用以下方法:
?

/* 獲取Spring上下文(以下代碼可利用工具類進行包裝) */ PageContext pageContext = (PageContext) this.getJspContext(); ServletContext servletContext = pageContext.getServletContext(); WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);/* 從上下文中獲取指定的Bean */ IAuthService authService = (IAuthService) wac.getBean("authService"); /** * 在Spring上下文中根據對象ID獲取對象引用 * * @param jspContext JSP上下文 * @param beanId 對象ID * @return 對象引用 */ @SuppressWarnings({"unchecked"}) public <T> T getBean(JspContext jspContext, String beanId) { T bean = null; PageContext pageContext = (PageContext) jspContext; if (pageContext != null) { ServletContext servletContext = pageContext.getServletContext(); if (servletContext != null) { WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); if (wac != null && wac.containsBean(beanId)) { bean = (T) wac.getBean(beanId); } } } return bean; }

3、結果

? ?我使用了第一種方式,注入的問題完美解決,注意繼承類不同時需要實現的方法也不一樣。

轉載于:https://my.oschina.net/githubhty/blog/1031080

總結

以上是生活随笔為你收集整理的自定义注解的spring注入问题的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。