little_shieh 2013-04-19 16:19
浏览 652
已采纳

Shiro+Struts2+Spring3 加上@RequiresPermissions 后@Autowired失效

@ParentPackage("all")
@Namespace("/project")
public class ProjectAction extends BaseAction {
public final static Logger logger = LoggerFactory
.getLogger(ProjectAction.class);

@Autowired(required=true)
private ProjectService projectService;

private String code;
private Project project;

public String getCode() {
    return code;
}

public void setCode(String code) {
    this.code = code;
}

public Project getProject() {
    return project;
}

public void setProject(Project project) {
    this.project = project;
}

@RequiresPermissions("SYS_PROJECT:FIND")
@Action(value = "findAll", results = { @Result(name = "success", type = "json", params = {
        "ignoreHierarchy", "false", "root", "dataMap" }) })
public String findAll() {
    Subject subject = SecurityUtils.getSubject();
    if (subject.isPermitted("SYS_PROJECT:FIND")){
        System.out.println("授权验证通过");
    }

    ProjectCriteria projectCriteria = new ProjectCriteria();
    Criteria criteria = projectCriteria.createCriteria();
    if (project == null) {
        project = new Project();
    }
    if (project.getCode() != null
            && !"".equals(project.getCode().trim())) {
        criteria.andCodeLike("%" + project.getCode() + "%");
    }
    if (project.getName() != null
            && !"".equals(project.getName().trim())) {
        criteria.andNameLike("%" + project.getName() + "%");
    }

    int total = 0;
    try
    {
        System.out.println(projectService==null);
        total = projectService.countByCriteria(projectCriteria);
    }catch(RuntimeException e){
        System.out.println(e);
    }
    dataMap.put("total", total);
    dataMap.put("rows", projectService.selectByCriteria(projectCriteria));
    return SUCCESS;
}

@RequiresPermissions("SYS_PROJECT:ADD")
@Action(value = "add", results = { @Result(name = "success", type = "json", params = {
        "ignoreHierarchy", "false", "root", "resultMap" }) })
public String add() {
    try {
        projectService.saveProject(project);
        resultMap.put("success", "true");
        resultMap.put("msg", "add success");
    } catch (Exception e) {
        resultMap.put("msg", "add error" + e.getStackTrace());
    }
    return SUCCESS;
}

@RequiresPermissions("SYS_PROJECT:UPD")
@Action(value = "toUpdate", results = { @Result(name = "success", type = "json", params = {
        "includeProperties", "project.*" }) })
public String toUpdate() {
    project = projectService.selectByPrimaryKey(this.getCode());
    return SUCCESS;
}

@RequiresPermissions("SYS_PROJECT:UPD")
@Action(value = "update", results = { @Result(name = "success", type = "json", params = {
        "ignoreHierarchy", "false", "root", "resultMap" }) })
public String update() {
    try {
        projectService.updateByPrimaryKey(project);
        resultMap.put("success", "true");
        resultMap.put("msg", "Update success");
    } catch (Exception e) {
        resultMap.put("msg", "Update error" + e.getMessage());
    }
    return SUCCESS;
}

@RequiresPermissions("SYS_PROJECT:DEL")
@Action(value = "delete", results = { @Result(name = "success", type = "json", params = {
        "ignoreHierarchy", "false", "root", "resultMap" }) })
public String delete() {
    try {
        projectService.deleteByPrimaryKey(this.getCode());
        resultMap.put("success", "true");
        resultMap.put("msg", "Delete success");
    } catch (Exception e) {
        resultMap.put("msg", "Delete error" + e.getMessage());
    }
    return SUCCESS;
}

}

加上@RequiresPermissions注释后可以获取到授权信息,但是projectService无法注入。
【授权验证通过
true
java.lang.NullPointerException】

删除所有的@RequiresPermissions后正常。前台可以获取到数据。

shiro的配置也没有错,

<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />

<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor">
    [color=red]<property name="proxyTargetClass" value="true" />  [/color]
</bean>

求解啊

  • 写回答

2条回答 默认 最新

  • jinnianshilongnian 2013-04-19 16:43
    关注

    1、从如下看 你使用了struts2-convention 插件扫描action 如如下的filter
    @ParentPackage("all")
    @Namespace("/project")
    public class ProjectAction extends BaseAction {

    <filter>
        <filter-name>struts2</filter-name>
        <filter-classfilter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
        <init-param>
            <param-name>actionPackages</param-name>
            <param-value>cn.javass</param-value>
        </init-param> 
    

    2、因此与spring集成了 但

    @Override
    public Object buildBean(String beanName, Map extraContext, boolean injectInternal) throws Exception {
    Object o;

        if (appContext.containsBean(beanName)) {
            o = appContext.getBean(beanName);[color=red] //拿不到bean[/color]
        } else {
            Class beanClazz = getClassInstance(beanName);
            o = buildBean(beanClazz, extraContext);[color=red] //所以创建了一个[/color]
        }
        if (injectInternal) {
            injectInternalBeans(o);
        }
        return o;
    }
    

    /**
    * @param clazz
    * @param extraContext
    * @throws Exception
    */
    @Override
    public Object buildBean(Class clazz, Map extraContext) throws Exception {
    Object bean;

        try {
            // Decide to follow autowire strategy or use the legacy approach which mixes injection strategies
            if (alwaysRespectAutowireStrategy) {[color=red]//默认false[/color]
                // Leave the creation up to Spring
                bean = autoWiringFactory.createBean(clazz, autowireStrategy, false);
                injectApplicationContext(bean);
                return injectInternalBeans(bean);
            } else {
                bean = autoWiringFactory.autowire(clazz, AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, false);[color=red] //只走构造器注入 [/color]
                bean = autoWiringFactory.applyBeanPostProcessorsBeforeInitialization(bean, bean.getClass().getName());
                // We don't need to call the init-method since one won't be registered.
                bean = autoWiringFactory.applyBeanPostProcessorsAfterInitialization(bean, bean.getClass().getName()); [color=red]//此时走了 预处理和 后处理器 所以代理类bean[/color]
                return autoWireBean(bean, autoWiringFactory); [color=red]// 然后autowire 此时给了代理对象[/color] 问题就处在这 可以认为是个bug
            }
        } catch (UnsatisfiedDependencyException e) {
            if (LOG.isErrorEnabled())
                LOG.error("Error building bean", e);
            // Fall back
            return autoWireBean(super.buildBean(clazz, extraContext), autoWiringFactory);
        }
    }
    

    解决方案
    1、不使用actionPackages
    而是 在类上加 @Controller @Scope 完全走spring

    2、使用setter注入 而不是字段 如

    private ProjectService projectService;

    @Autowired(required=true)
    public void setProjectService() {

    }

    3、修改bug
    把autowire 放到预处理和后处理之前

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 依据报错在原代吗格式的基础上解决问题
  • ¥15 在虚拟机中安装flash code
  • ¥15 单片机stm32f10x编写光敏电阻调节3.3伏大功率灯亮度(光强越大灯越暗,白天正常光强灯不亮,使用ADC,PWM等模块)望各位找一下错误或者提供一个可实现功能的代码
  • ¥20 verilog状态机方法流水灯
  • ¥15 pandas代码实现不了意图
  • ¥15 GD32H7 从存储器到外设SPI传输数据无法重复启用DMA
  • ¥25 LT码在高斯信道下的误码率仿真
  • ¥45 渲染完成之后将物体的材质贴图改变,自动化进行这个操作
  • ¥15 yolov5目标检测并显示目标出现的时间或视频帧
  • ¥15 电视版的优酷可以设置电影连续播放吗?