Dar*_*ari 6 java spring spring-mvc session-scope spring-bean
我开发了一个 Spring Web-MVC 应用程序。我的项目中有一些办公室。每个用户属于一个办公室。user.getOfficeType()返回一个表示用户办公室类型的整数。如果 office 类型为 1,则用户属于 Office1 等。但是我想将经过身份验证的用户的 office 注入我的服务类:
class MyService{
@Autowired
Office currentOffice;
...
}
Run Code Online (Sandbox Code Playgroud)
我阅读了 Spring 文档。我需要一个会话范围的 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>
Run Code Online (Sandbox Code Playgroud)
我有Office接口的三个实现。一旦用户请求资源,我想知道他的办公室。所以我需要将他的会话范围的 Office 注入我的服务类。但是我不知道如何根据用户的办公室来实例化它。请帮忙!
我找到了解决办法!我声明了一个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();
}
}
Run Code Online (Sandbox Code Playgroud)
在我的服务课程中,我注入了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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3574 次 |
| 最近记录: |