Liferay Hook 中如何调用spring实例化的对象

阅读更多
自己新建的Hook,它是通过配置类名的方式,由Liferay热加载的,所以Hook当中的bean不能通过spring来配置,而我又的确想要spring创建的那些bean,因为这些bean可能创建比较复杂,甚至还包括了一些要传入的property配置信息,该问题可通过取巧,创建一个SpringBeanUtil来实现。RememberMeAutoLoginHook是我的Hook。


public class RememberMeAutoLoginHook implements AutoLogin {

private RememberMeService rememberMeService;

private CookieGenerator cookieGenerator;

@Override
public String[] login(HttpServletRequest request, HttpServletResponse response)
throws AutoLoginException {
System.out.println("RememberMeAutoLoginHook test......"+cookieGenerator);
String credentials[] = new String[2];
//1. Check if rememberMe cookie exists, If so, get the  token from the cookie
// rememberMeService.authenticate (AuthRequest)
String token = null;
Cookie[] cookies = request.getCookies();
if(cookies!=null) {
for (int i = 0; i < cookies.length; i++)   
   {   
      Cookie c = cookies[i];       
      if(c.getName().equalsIgnoreCase(getCookieGenerator().getCtCookiePropertyValue()))   
      {   
      token = c.getValue();   
       }  
   }
}

if (token != null) {
AuthResult authResult = getRememberMeService().authenticate(token);
if (authResult.isSuccess()) {
        Cookie clearTrust = getCookieGenerator().
        createMasterClearTrustCookie(request.getServerName(), authResult.getToken());
response.addCookie(clearTrust);
}else {
return null;
}
}else {
return null;
}

return credentials;
}

public RememberMeService getRememberMeService() {
if (rememberMeService == null) {
rememberMeService = SpringBeanUtil.getInstance().getRememberMeService();
}
System.out.println("RememberMeAutoLoginHook rememberMeService:"+rememberMeService);
return rememberMeService;
}

public CookieGenerator getCookieGenerator() {
if (cookieGenerator == null) {
cookieGenerator = SpringBeanUtil.getInstance().getCookieGenerator();
}
System.out.println("RememberMeAutoLoginHook cookieGenerator:"+cookieGenerator);
return cookieGenerator;
}

}


public class SpringBeanUtil { 
   
    private static SpringBeanUtil instance = new SpringBeanUtil(); 
     
private static RememberMeService rememberMeService;

private static CookieGenerator cookieGenerator;
     
    private SpringBeanUtil () {} 
 
    public static SpringBeanUtil getInstance() { 
        return instance; 
    } 
     
    public void setInstance(SpringBeanUtil newInstance) { 
        instance = newInstance; 
    } 
 
    public RememberMeService getRememberMeService() { 
        return rememberMeService; 
    } 
     
    public void setRememberMeService(RememberMeService rememberMeService) { 
        SpringBeanUtil.rememberMeService = rememberMeService; 
    } 
   
    public CookieGenerator getCookieGenerator() { 
        return cookieGenerator; 
    } 
     
    public void setCookieGenerator(CookieGenerator cookieGenerator) { 
        SpringBeanUtil.cookieGenerator = cookieGenerator; 
    } 
   
     



在pring-context.xml中配置如下:

        
        

你可能感兴趣的:(spring,liferay)