添加global-method-security命名空间时,Spring不会看到@Transactional

时间:2012-09-26 18:34:29

标签: java spring hibernate spring-mvc spring-security

我创建了一个负责通过dao与数据库联系的服务。我使用@Transactional注释来处理事务。

@Service("aclService")
public class HibernateAclServiceImpl implements HibernateAclService{

private final Log logger = LogFactory.getLog(HibernateAclServiceImpl.class);
@Autowired
private AclObjectIdentityDao objectIdentityDao ;
private PermissionFactory permissionFactory = new DefaultPermissionFactory();
@Autowired
private AclCache aclCache;
@Autowired
private PermissionGrantingStrategy grantingStrategy;
@Autowired
private AclAuthorizationStrategy aclAuthorizationStrategy;

private final Field fieldAces = FieldUtils.getField(AclImpl.class, "aces");

@Override
@Transactional
public List<ObjectIdentity> findChildren(ObjectIdentity parentIdentity) {
    AclObjectIdentity aclObjectIdentity = objectIdentityDao
            .get((Long) parentIdentity.getIdentifier());
    List<ObjectIdentity> list = new ArrayList<ObjectIdentity>(
            aclObjectIdentity.getChildren().size());
    for (AclObjectIdentity aoid : aclObjectIdentity.getChildren()) {
        final ObjectIdentity oid = new ObjectIdentityImpl(aoid.getObjectClass().getClazz());
        list.add(oid);
    }
    return list;
}

@Override
@Transactional
public Acl readAclById(ObjectIdentity object) throws NotFoundException {
    final Map<ObjectIdentity, Acl> objects = readAclsById(Arrays.asList(object), null);
    return objects.get(object);
}

@Override
@Transactional
public Acl readAclById(ObjectIdentity object, List<Sid> sids)
        throws NotFoundException {
    Map<ObjectIdentity, Acl> objects = readAclsById(Arrays.asList(object), sids);
    return objects.get(object);
}


@Override
@Transactional
public Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects)
        throws NotFoundException {
    return readAclsById(objects, null);
}

@Override
public Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects,
        List<Sid> sids) throws NotFoundException {
    Map<ObjectIdentity, Acl> result = new HashMap<ObjectIdentity, Acl>();
    Set<Long> objectsToLoad = new HashSet<Long>();

    for (int i = 0; i < objects.size(); i++) {
        final ObjectIdentity oid = objects.get(i);
        boolean aclFound = false;

        if (result.containsKey(oid)) {
            aclFound = true;
        }

        if (!aclFound) {
            Acl acl = aclCache.getFromCache(oid);

            if (acl != null) {
                if (acl.isSidLoaded(sids)) {
                    result.put(acl.getObjectIdentity(), acl);
                    aclFound = true;
                } else {
                    throw new IllegalStateException(
                            "Error: SID-filtered element detected when implementation does not perform SID filtering "
                                    + "- have you added something to the cache manually?");
                }
            }
        }
        if (!aclFound) {
            objectsToLoad.add((Long) oid.getIdentifier());
        }
    }

    if (objectsToLoad.size() > 0) {
        lookupAcl(result, objectsToLoad);
    }
    return result;
}
public void lookupAcl(Map<ObjectIdentity, Acl> map, Set<Long> objects){
    final List<AclObjectIdentity> aoids = objectIdentityDao.getList(objects);
    final Map<Long, Long> parents = new HashMap<Long, Long>();
    for(AclObjectIdentity aoid : aoids){
        if(aoid.isEntriesInheriting()){
            parents.put(aoid.getId(), aoid.getParent().getId());
        }
    }
    if(parents.size() > 0){
        lookupAcl(map, (Set<Long>)parents.values());
    }
    for(AclObjectIdentity aoid : aoids){
        if(map.containsKey(aoid.getId()))
            continue;
        final Acl parentAcl = map.get(parents.get(aoid.getId()));
        final Acl acl = new AclImpl(new ObjectIdentityImpl(aoid.getObjectClass().getClazz(), aoid.getId()), aoid.getId(), aclAuthorizationStrategy, grantingStrategy, parentAcl, null, aoid.isEntriesInheriting(), new PrincipalSid(aoid.getOwnerSid().getSid()));



        List<AccessControlEntryImpl> aces = new ArrayList<AccessControlEntryImpl>(aoid.getAclEntries().size());
        for(AclEntry aclEntry : aoid.getAclEntries()){
            final Permission permission = permissionFactory.buildFromMask(aclEntry.getMask());
            aces.add(new AccessControlEntryImpl(aclEntry.getId(), acl, new PrincipalSid(aclEntry.getSid().getSid()), permission, aclEntry.isGranting(), aclEntry.isAuditSuccess(), aclEntry.isAuditFailure()));
        }
        setAces((AclImpl) acl, aces);
        aclCache.putInCache((AclImpl) acl);
    }
}

private void setAces(AclImpl acl, List<AccessControlEntryImpl> aces) {
    try {
        fieldAces.set(acl, aces);
    } catch (IllegalAccessException e) {
        throw new IllegalStateException("Could not set AclImpl entries", e);
    }
}

}

以下是我的'app-context.xml'文件的一部分

<security:global-method-security  pre-post-annotations="enabled">
    <security:expression-handler ref="expressionHandler" />
</security:global-method-security>
<bean id="expressionHandler"
    class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">
    <property name="permissionEvaluator" ref="permissionEvaluator" />
    <property name="roleHierarchy" ref="roleHierarchy" />
</bean>

<bean class="org.springframework.security.acls.AclPermissionEvaluator"
    id="permissionEvaluator">
    <constructor-arg ref="aclService" />
</bean>

现在我调用服务的功能,例如。从控制器它会抛出错误org.hibernate.HibernateException: No Session found for current thread。但是当我评论时,一切都很好(交易没问题)

<security:global-method-security pre-post-annotations="enabled"> <security:expression-handler ref="expressionHandler" /> </security:global-method-security>

我检查了所有内容,并将有问题的代码缩小到上面的内容。有谁知道为什么会这样?

1 个答案:

答案 0 :(得分:7)

我不确定global-method-security是如何在幕后实现的,但BeanPostProcessors有一个鲜为人知的副作用 - 由BeanPostProcessor直接引用的任何bean,或者由BPP引用的东西引用,不符合AOP自动代理的条件

  

BeanPostProcessors和AOP自动代理

     

实现BeanPostProcessor接口的类是特殊的,容器会对它们进行不同的处理。直接引用的所有BeanPostProcessors和bean都会在启动时实例化,这是ApplicationContext的特殊启动阶段的一部分。接下来,所有BeanPostProcessors都以排序方式注册,并应用于容器中的所有其他bean。因为AOP自动代理是作为BeanPostProcessor本身实现的,所以BeanPostProcessors和它们直接引用的bean都没有资格进行自动代理,因此没有编织方面。

     

对于任何此类bean,您应该看到一条信息性日志消息:“Bean foo不适合所有BeanPostProcessor接口处理(例如:不符合自动代理条件)”。

(source)

这意味着如果在引用BeanPostProcessor时加载的bean中有@Transactional,则该注释实际上会被忽略。

解决方案通常是,如果您需要在Bean中引入BeanPostProcessor时需要加载事务行为,则需要使用非AOP事务定义 - 即使用TransactionTemplate。

您可以将org.springframework记录器上的日志记录调到DEBUG,并验证是否正在为aclService bean输出此消息。