自定义注解的spring注入问题

   我就我遇到的自定义注解无法注入的问题整理一下:

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;
    }
 
    @Override
    protected 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值