2015-10-16 113 views
3

我已经开发了一个Spring Web的MVC应用程序作用域bean。我的项目中有一些办公室。每个用户都属于一个办公室。 user.getOfficeType()返回一个代表用户的办公类型的整数。如果办公室类型为1,用户所属OFFICE1等 不过,我想验证用户的办公注入我的服务类:如何创建一个春季会议基于用户属性

class MyService{ 
    @Autowired 
    Office currentOffice; 
    ... 
} 

我读了春天文档。我需要一个会话scoped bean来将它注入到我的服务类中。

的applicationContext.xml

<mvc:annotation-driven /> 
<tx:annotation-driven transaction-manager="hibernateTransactionManager"/> 
<context:annotation-config /> 
<context:component-scan base-package="com.package.controller" /> 
<context:component-scan base-package="com.package.service" /> 
... 
<bean id="office" class="com.package.beans.Office" scope="session"> 
    <aop:scoped-proxy/> 
</bean> 

enter image description here

我有Office接口的三种实现。一旦用户请求资源,我想知道他的办公室。所以我需要将他的会话范围的Office注入到我的服务类中。但我不知道如何根据用户的办公室实例化它。请帮忙!

+0

是用户会话bean呢? –

+0

不,它是一个实体。我可以用'SecurityContextHolder.getContext()来访问它。getAuthentication()' –

回答

2

我找到了解决办法!我宣布为OfficeContext一个包装Office并实现它。

@Component 
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) 
public class OfficeContext implements InitializingBean, Office { 

    private Office office; 

    @Autowired 
    private UserDao userDao; 

    @Autowired 
    private NoneOffice noneOffice; 
    @Autowired 
    private AllOffice allOffice; 
    @Autowired 
    private TariffOffice tariffOffice; 
    @Autowired 
    private ArzeshOffice arzeshOffice; 

    public Office getOffice() { 
     return this.office; 
    } 

    @Override 
    public void afterPropertiesSet() throws Exception { 
     Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 
     if (auth.isAuthenticated()) { 
      String name = auth.getName(); //get logged in username 
      JUser user = userDao.findByUsername(name); 
      if (user != null) { 
       this.office = noneOffice; 
      } else { 
       OfficeType type = user.getOfficeType(); 
       switch (type) { 
        case ALL: 
         this.office = allOffice; 
         break; 
        case TARIFF: 
         this.office = tariffOffice; 
         break; 
        case ARZESH: 
         this.office = arzeshOffice; 
         break; 
        default: 
         this.office = noneOffice; 
       } 
      } 
     } else { 
      this.office = noneOffice; 
     } 

    } 

    @Override 
    public OfficeType getType() { 
     return office.getType(); 
    } 

    @Override 
    public String getDisplayName() { 
     return office.getDisplayName(); 
    } 

} 

并且在我的服务类中我注入了OfficeContext

@Service 
public class UserService { 

    @Autowired 
    UserDao userDao; 

    @Autowired 
    OfficeContext office; 

    public void persist(JUser user) { 
     userDao.persist(user); 
    } 

    public void save(JUser user) { 
     userDao.save(user); 
    } 


}