当前位置: 移动技术网 > IT编程>开发语言>Java > spring security国际化及UserCache的配置和使用

spring security国际化及UserCache的配置和使用

2019年07月19日  | 移动技术网IT编程  | 我要评论

国际化配置

<!-- 定义上下文返回的消息的国际化 --> 
<bean id="messagesource" 
  class="org.springframework.context.support.reloadableresourcebundlemessagesource"> 
  <property name="basename" 
    value="classpath:config/messages_zh_cn"/> 
</bean> 

basename中配置的是消息文件的路径

在spring-security-core-3.2.0.m1.jar包中的org.springframework.security下可以找到国际化文件,可以直接拿来,这个类也可以用在项目中

@autowired 
private messagesource messagesource; 

这样就可以在类中引如messagesource使用了,messagesource提供了下面三个方法

1.string getmessage(string code, object[] args, string defaultmessage, locale locale);  

2.string getmessage(string code, object[] args, locale locale) throws nosuchmessageexception;  

3.string getmessage(messagesourceresolvable resolvable, locale locale) throws nosuchmessageexception;  

比如我们在property文件中定义了如下消息

1.userdetails.islocked=用户已被锁定  

2.userdetails.usernotfound=用户{0}不存在  

然后使用getmessage方法

getmessage("userdetails.islocked",null,null) //用户已被锁定
getmessage("userdetails.islocked",new object[]{“admin”},null) //用户admin不存在

usercache配置,通过ecahe实现

<!-- 启用用户的缓存功能 --> 
<bean id="usercache" 
  class="org.springframework.security.core.userdetails.cache.ehcachebasedusercache"> 
  <property name="cache" ref="userehcache" /> 
</bean> 
<bean id="userehcache" class="org.springframework.cache.ehcache.ehcachefactorybean"> 
  <property name="cachename" value="usercache" /> 
  <property name="cachemanager" ref="cachemanager" /> 
</bean>  
<bean id="cachemanager" 
class="org.springframework.cache.ehcache.ehcachemanagerfactorybean" /> 

ehcache.xml

<cache 
  name="usercache" 
  maxelementsinmemory="100" 
  eternal="false" 
  timetoidleseconds="600" 
  timetoliveseconds="3600" 
  overflowtodisk="true" 
/> 
注入ecache
@autowired 
private usercache usercache; 

这样在程序中就可以通过

this.usercache.getuserfromcache(username);获取到缓存中的用户对象

用户对象为userdetails类型

总结

以上所述是小编给大家介绍的spring security国际化及usercache的配置和使用,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网