【问题标题】:Spring and manually created DAOs how to refactor to enable hasPermisions on such DAOs objectsSpring 和手动创建的 DAO 如何重构以在此类 DAO 对象上启用 hasPermisions
【发布时间】:2013-05-27 14:05:48
【问题描述】:

我有这样的道观

public class EntityDao<T> {

    private Class clazz;
    private SessionFactory sessFactory;

    public EntityDao(Class clazz, SessionFactory sessFactory) {
        this.clazz = clazz;
        this.sessFactory = sessFactory;

    }
.... dao methods 
}

以及用于检索和存储特定 dao 的工厂

EntityBeanDaoFactory {

private HashMap<EntityDaoType, EntityDao> daoMap = new HashMap<EntityDaoType, EntityDao>();
// return dao from daoMap if exists a if not create it and put it in the map then return dao
public EntityDao createDao(EntityDaoType entityType)  {
 switch (entityType) {
        case mySpecialDaoTYPE:
            if (!daoMap.containsKey(entityType)) {
                    EntityDao<Type> mySpecialDao = new EntityDao(Type.class, sessFactory);
                    daoMap.put(entityType, mySpecialDao);
                }
                 return daoMap.get(entityType);
}

}

现在我想用 @PreAuthorize("hasPermission()") 注释 dao 方法,但是 spring 不知道以这种方式创建的 daos,我无法立即重构整个项目,所以我创建了 dao ,就这样我需要在 aplicationContectxt.xml 中使用注释

<bean id="mySpecialDao" class="..EntityDao" >
    <constructor-arg>
        <value>myClass</value> 
    </constructor-arg>
    <constructor-arg ref="sessionFactory" />
</bean>

在工厂内,我改变了创建这种特定 dao 的行为

     if (!daoMap.containsKey(entityType)) {
         EntityDao<Class> dao = (EntityDao<Class>) AppContext.getApplicationContext().getBean("mySpecialDao");
                daoMap.put(entityType, dao);
            }

有没有更好的方法让 spring 了解我的 DAO ?我的意思是有没有办法让 Spring 意识到手动创建的实例?

【问题讨论】:

    标签: spring spring-security


    【解决方案1】:

    您可以通过使用 AspectJ 的 Spring AOP 支持来做到这一点。在这里阅读更多:http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/aop.html#aop-atconfigurable

    启用此功能后,Spring 将知道使用 Configurable 注解注解的类创建的任何实例。然后 Spring 将能够识别 PreAuthorize 注释。

    【讨论】:

      【解决方案2】:

      为什么需要工厂来创建 DAO?这就是 Spring 应用程序上下文。

      您似乎想限制使用基于角色的安全性调用 DAO 方法的能力。我认为这很好,并且可以做到,但您不必限制 DAO 的创建。使用 Spring 创建它,然后限制访问。你的方式太过分了,没必要。

      【讨论】:

      • 那里的工厂已经全部建成,而且在很多地方都进行了硬编码,因此很难摆脱它(不是我 :-))。我不需要限制对 dao 或其方法的调用,而是根据当前用户和目标实体 ID 实现某种 ACL,因此我有自己的 permisionEvaluator (hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission))
      猜你喜欢
      • 1970-01-01
      • 2016-01-04
      • 2011-11-11
      • 1970-01-01
      • 1970-01-01
      • 2014-03-19
      • 2013-08-31
      • 1970-01-01
      • 2011-01-27
      相关资源
      最近更新 更多