Spring拡張点

12392 ワード

Spring拡張点
1.IOC生成類フルネーム

name-generator="cn.com.demo.framework.spring.context.annotation.FullNameBeanNameGenerator" use-default-filters="false">

public class FullNameBeanNameGenerator extends AnnotationBeanNameGenerator{

@Override
protected String buildDefaultBeanName(BeanDefinition definition) {
return definition.getBeanClassName();
}

}

2.マッピングを生成するURLの大文字と小文字を変換



public class CocRequestMappingHandlerMapping extends RequestMappingHandlerMapping{

/** Controller */
private static final String CONTROLLER_SUFFIX = "Controller";

/** url */
private String basePackage;

//
private boolean useSuffixPatternMatch = true;
private boolean useTrailingSlashMatch = true;
private final List fileExtensions = new ArrayList();

/**
* Look for handler methods in a handler.
* @param handler the bean name of a handler or a handler instance
*/
protected void detectHandlerMethods(final Object handler) {
//Assert.notNull(this.basePackage, "must config basePackage!");
super.detectHandlerMethods(handler);
}

/**
* createRequestMappingInfo ,
* Uses method and type-level @{@link RequestMapping} annotations to create
* the RequestMappingInfo.
*
* @return the created RequestMappingInfo, or {@code null} if the method
* does not have a {@code @RequestMapping} annotation.
*
* @see #getCustomMethodCondition(Method)
* @see #getCustomTypeCondition(Class)
*/
@Override
protected RequestMappingInfo getMappingForMethod(Method method, Class> handlerType) {
RequestMappingInfo info = null;
RequestMapping methodAnnotation = AnnotationUtils.findAnnotation(method, RequestMapping.class);
if (methodAnnotation != null) {
RequestCondition> methodCondition = getCustomMethodCondition(method);
info = createRequestMappingInfo(methodAnnotation, methodCondition, method, handlerType);
RequestMapping typeAnnotation = AnnotationUtils.findAnnotation(handlerType, RequestMapping.class);
if (typeAnnotation != null) {
RequestCondition> typeCondition = getCustomTypeCondition(handlerType);
info = createRequestMappingInfo(typeAnnotation, typeCondition, method, handlerType).combine(info);
}

}
return info;
}

/**
* controller
*/
private RequestMappingInfo createRequestMappingInfo(RequestMapping annotation, RequestCondition> customCondition, Method method, Class> handlerType) {

String[] patterns = resolveEmbeddedValuesInPatterns(annotation.value());

//@RequestMapping value, coc
if( patterns.length==0 ){
StringBuilder p = new StringBuilder();
if (this.basePackage != null) {
String packageName = ClassUtils.getPackageName(handlerType);
if (packageName.startsWith(this.basePackage)) {
String subPackage = packageName.substring(this.basePackage.length()).replace('.', '/');
if( subPackage.endsWith("/controller") ){
// /backup/controller /controller
subPackage = subPackage.substring(0,subPackage.indexOf("/controller"));
}
p.append(subPackage.toLowerCase());
p.append("/");
}
}

//
String className = handlerType.getSimpleName();
className = (className.endsWith(CONTROLLER_SUFFIX) ?
className.substring(0, className.lastIndexOf(CONTROLLER_SUFFIX)) : className);

p.append(className.toLowerCase()).append("/");//
p.append(method.getName().toLowerCase());//
patterns = new String[]{p.toString()};
}

return new RequestMappingInfo(
new PatternsRequestCondition(patterns, getUrlPathHelper(), getPathMatcher(),
this.useSuffixPatternMatch, this.useTrailingSlashMatch, this.fileExtensions),
new RequestMethodsRequestCondition(annotation.method()),
new ParamsRequestCondition(annotation.params()),
new HeadersRequestCondition(annotation.headers()),
new ConsumesRequestCondition(annotation.consumes(), annotation.headers()),
new ProducesRequestCondition(annotation.produces(), annotation.headers(), getContentNegotiationManager()),
customCondition);
}

//----------------------set get
public void setBasePackage(String basePackage) {
this.basePackage = basePackage;
}

public void setUseSuffixPatternMatch(boolean useSuffixPatternMatch) {
this.useSuffixPatternMatch = useSuffixPatternMatch;
}

public void setUseTrailingSlashMatch(boolean useTrailingSlashMatch) {
this.useTrailingSlashMatch = useTrailingSlashMatch;
}


}

3.パラメータカスタムタイプ変換











































public class StringToDateConverter implements Converter{

@Override
public Date convert(String source) {

if( source==null || source.length()==0 )
return null;

int length = source.length();

switch (length) {
case 5:
return parse("HH:mm", source);
case 10:
return parse("yyyy-MM-dd", source);

case 19:
case 21:
case 22:
return parse("yyyy-MM-dd HH:mm:ss", source);

case 23:
return parse("yyyy-MM-dd'T'HH:mm:ss.SSS", source);
case 28:
try {
return new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy", Locale.US).parse(source);
} catch (ParseException e) {
throw new RuntimeException(" ,datestr:" + source, e);
}
default:
throw new RuntimeException("Unsupport Date Format: " + source);
}
}

/**
* date
*/
private Date parse(String format, String date){
try {
return new SimpleDateFormat(format).parse(date);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}

public class CrudHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver{

@Override
public boolean supportsParameter(MethodParameter parameter) {
Class> paramType = parameter.getParameterType();
return QueryParam.class.isAssignableFrom(paramType);
}

@Override
public Object resolveArgument(MethodParameter parameter,
ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
WebDataBinderFactory binderFactory) throws Exception {

Class> paramType = parameter.getParameterType();

//
QueryParam p = parseQueryParam(parameter, webRequest);
return p;
}

/**
*

*/
@SuppressWarnings("serial")
private QueryParam parseQueryParam(MethodParameter parameter, NativeWebRequest webRequest){
QueryParam p = new QueryParam();
//
p.setStart(getInteger(webRequest, "start"));
p.setLimit(getInteger(webRequest, "limit"));
String sort = webRequest.getParameter("sort");
if(StringUtils.isNotBlank(sort)){
SortExpression[] orderBy = JsonConverterUtils.getJc().fromJson(sort, SortExpression[].class);
DefaultConvertName dcn = new DefaultConvertName();
orderBy[0].setProperty(dcn.convertToColumnName(orderBy[0].getProperty()));
p.setSort(orderBy[0].toSqlString());
}
return p;
}

/**
*
*/
private Integer getInteger(NativeWebRequest webRequest, String name){
String p = webRequest.getParameter(name);

if( p==null || p.length()==0 )
return null;

return Integer.valueOf(p);
}

/**
* get ,
*/
private String encodeParameter(NativeWebRequest webRequest, String paramName){
HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
String p = webRequest.getParameter(paramName);
if( "GET".equalsIgnoreCase(request.getMethod())){
return RequestUtil.encodeParameter(p);
}
return p;
}

}

public class LongToStringJsonSerializer extends JsonSerializer {

@Override
public Class handledType() {
return Long.class;
}

@Override
public void serialize(Long value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {
jgen.writeString(value.toString());
}

}

4.カスタム例外ブロッカー

public class ProjectHandlerExceptionResolver implements HandlerExceptionResolver{

private final Logger logger = LoggerFactory.getLogger(getClass());

/** json */
@Resource private JsonConverter jsonConverter;

@Resource private LogManageService logManageService;

@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) {

return null;
}

/**
*
* ExtForm StandardSubmit

* X-Requested-With StandardSubmit
*/
private boolean isExtFormStandardSubmit(HttpServletRequest request){
return request.getParameter("X-Requested-With")!=null;
}
}