2016-09-21 95 views
1

我是新來的春天。我想爲下面的代碼編寫一個bean定義。彈簧整合的豆的定義

package com.abc.common.filter; 

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

import org.apache.log4j.Logger; 

public class RegexFilter implements Filter<String> { 

    Logger logger = Logger.getLogger(RegexFilter.class); 
    private Pattern regex; 
    private String lastMatch; 

    public RegexFilter(String regexString) { 
     this.lastMatch = null; 
     regex = Pattern.compile(regexString, Pattern.UNICODE_CHARACTER_CLASS); 
    } 

    @Override 
    public boolean matches(String text) { 
     text = text.toLowerCase(); 
     if (text == null) { 
     logger.error("No text set for matching!"); 
     return false; 
     } 

     Matcher matcher = regex.matcher(text); 
     if (matcher.find(0)) {// always start at index 0 
     this.lastMatch = matcher.group(); 
     if (logger.isDebugEnabled()) { 
      logger.debug(matcher.group() + " found!"); 
     } 
     return true; 
     } 

     return false; 
    } 

    public String getLastMatch(){ 
     return this.lastMatch; 
    } 

} 

我卡在這行後,我不知道如何包含索引或名稱?對索引和值進行更多的澄清將更有幫助。

<bean id="regexfilter" class="com.abc.common.filter.RegexFilter" /> 
    <constructor-arg name="regexString" /> 
     </bean> 
+0

你會得到什麼錯誤?或者你在哪裏遇到麻煩? – reos

回答

0

基於註解莊園用純Java中,你可以做這樣的事情:

@Configuration 
public class ApplicationConfig { 

    @Bean 
    public Filter regexFilter() { 
     return new RegexFilter("value_for_the_regex_filter"); 
    } 
} 

或簡單地說:

@Service 
public class RegexFilter implements Filter<String> { 
    ... 
}