2015-10-16 70 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); 
    } 


}