spring的基于java的项目配置示例2
程序员文章站
2022-07-10 15:10:33
...
import com.xxx.support.config.AbstractAppInitializer; import com.xxx.support.config.BaseRootConfig; public class AppInitializer extends AbstractAppInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class[] { BaseRootConfig.class, RootConfig.class }; } @Override protected Class<?>[] getServletConfigClasses() { return new Class[] { MvcConfig.class }; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } }
import javax.servlet.Filter; import javax.servlet.ServletRegistration; import org.sitemesh.config.ConfigurableSiteMeshFilter; import org.springframework.web.filter.CharacterEncodingFilter; import org.springframework.web.filter.DelegatingFilterProxy; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public abstract class AbstractAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Filter[] getServletFilters() { CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter(); encodingFilter.setEncoding("UTF-8"); encodingFilter.setForceEncoding(true); DelegatingFilterProxy shiroFilter = new DelegatingFilterProxy(); // shiroFilter.setBeanName("shiroFilter"); shiroFilter.setTargetBeanName("shiroFilter"); shiroFilter.setTargetFilterLifecycle(true); ConfigurableSiteMeshFilter siteMEshFilter = new ConfigurableSiteMeshFilter(); return new Filter[] { encodingFilter, shiroFilter, siteMEshFilter }; } // @Override // public void onStartup(ServletContext servletContext) throws ServletException { // servletContext.addListener(new SessionListener()); // super.onStartup(servletContext); // } @Override protected void customizeRegistration(ServletRegistration.Dynamic reg) { reg.setInitParameter("throwExceptionIfNoHandlerFound", "true"); } }
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.PropertySources; import org.springframework.core.env.Environment; import org.springframework.core.task.TaskExecutor; import org.springframework.data.redis.connection.RedisClusterConfiguration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.serializer.StringRedisSerializer; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; @Configuration @PropertySources({ @PropertySource(value="classpath:/hs-admin-support-properties/hs-admin-support-env.properties"), @PropertySource(value="file:${appHome}/hs-admin-support-env.properties", ignoreResourceNotFound = true) }) @Import({ RedisSessionConfig.class }) public class BaseRootConfig { private static final Logger logger = LoggerFactory.getLogger(BaseRootConfig.class); @Autowired private Environment env; @Bean public TaskExecutor taskExecutor() { ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); taskExecutor.setCorePoolSize(4); taskExecutor.setMaxPoolSize(8); taskExecutor.setQueueCapacity(16); return taskExecutor; } private List<String> redisNodes() { String redisNodesStr = env.getRequiredProperty("hs.admin.support.redis.server.list"); logger.info("Redis nodes [{}]", redisNodesStr); String[] nodeArr = StringUtils.split(redisNodesStr, ','); if (nodeArr != null) { return Arrays.asList(nodeArr); } else { return new ArrayList<>(); } } @Bean public RedisConnectionFactory redisConnectionFactory() { List<String> redisNodes = redisNodes(); RedisClusterConfiguration redisClusterConfig = new RedisClusterConfiguration(redisNodes); JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(redisClusterConfig); jedisConnectionFactory.setTimeout(2000 * 5); return jedisConnectionFactory; } @Bean("redisTemplate") public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setConnectionFactory(redisConnectionFactory); redisTemplate.afterPropertiesSet(); return redisTemplate; } @Bean("stringRedisTemplate") public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) { return new StringRedisTemplate(redisConnectionFactory); } @Bean("shiroRedisTemplate") public RedisTemplate<?, ?> shiroRedisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<?, ?> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); redisTemplate.afterPropertiesSet(); return redisTemplate; } }
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; import org.springframework.session.web.http.CookieSerializer; import org.springframework.session.web.http.DefaultCookieSerializer; @Configuration @EnableRedisHttpSession(redisNamespace = "hs:admin", maxInactiveIntervalInSeconds = 3600) public class RedisSessionConfig { /** * 默认的配置中导致 ignoreUnresolvablePlaceholders = false<br> * 最终导致本地开发环境中 appHome 找不到而报错 * * @return */ @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer(); pspc.setIgnoreResourceNotFound(true); pspc.setIgnoreUnresolvablePlaceholders(true); return pspc; } @Bean public CookieSerializer cookieSerializer() { DefaultCookieSerializer serializer = new DefaultCookieSerializer(); serializer.setCookieName("HS_ADMIN_SSID"); // serializer.setCookieName("JSESSIONID"); serializer.setCookiePath("/"); // serializer.setDomainNamePattern("^.+?\\.(\\w+\\.[a-z]+)$"); // serializer.setDomainNamePattern("^.+?(\\.(\\w+\\.[a-z]+))$"); return serializer; } }
import java.util.Properties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.PropertiesFactoryBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan.Filter; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.FilterType; import org.springframework.context.annotation.ImportResource; import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.PropertySources; import org.springframework.core.env.Environment; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ControllerAdvice; import com.xxxx.springutil.failfast.FailFastFromPropertyAndSystemProperty; import com.xxx.support.redis.JedisClusterFactoryBean; import redis.clients.jedis.JedisCluster; @Configuration @ComponentScan( basePackages = { "com.xxxx.admin.support", "com.xxxx.cms.admin" }, excludeFilters = { @Filter(type = FilterType.ANNOTATION, value = Controller.class), @Filter(type = FilterType.ANNOTATION, value = ControllerAdvice.class) } ) @PropertySources({ @PropertySource(value = "classpath:/hs-cms-admin-properties/hs-cms-admin-env.properties"), @PropertySource(value = "file:${appHome}/hs-cms-admin-env.properties", ignoreResourceNotFound = true) }) @ImportResource({ "classpath:/hs-admin-srv-client-config/context.xml", // "classpath:/hs-cms-srv-client-config/cms-redis.xml", "classpath:/hs-cms-srv-client-config/context-cms-admin.xml", "classpath:/hs-cms-admin-config/spring-memcached.xml", "classpath:/hs-cms-admin-config/dubbo-config.xml", "classpath:/apiClient/spring-hq-context.xml", "classpath:/hs-mq-client-config/spring-jms-common.xml", "classpath:/hs-mq-client-config/spring-jms-consumer.xml" }) public class RootConfig { @Autowired private Environment env; @Bean public FailFastFromPropertyAndSystemProperty failFastFromPropertyAndSystemProperty() { FailFastFromPropertyAndSystemProperty ff = new FailFastFromPropertyAndSystemProperty(); ff.setIfExistSystemPropertyVar("appHome"); ff.setPropertyValueBySpring(env.getProperty("hs.cms.admin.env", "dev")); ff.setStopWhenPropertyEqualsThisValue("dev"); return ff; } @Bean public PropertiesFactoryBean appProps() { PropertiesFactoryBean pfb = new PropertiesFactoryBean(); pfb.setSingleton(true); Properties properties = new Properties(); properties.put("appEnv", env.getProperty("hs.cms.admin.env", "dev")); properties.put("hostRes", env.getProperty("hs.cms.admin.host.res", "https://r.xxxx.com")); pfb.setProperties(properties); return pfb; } @Bean public JedisCluster jedisCluster() throws Exception { JedisClusterFactoryBean jedisClusterFactoryBean = new JedisClusterFactoryBean(); jedisClusterFactoryBean.setServers(env.getProperty("hs.cms.admin.redis.server.list")); jedisClusterFactoryBean.setTimeout(2000); return (JedisCluster) jedisClusterFactoryBean.getObject(); } }
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.stereotype.Component; import org.springframework.stereotype.Controller; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.view.XmlViewResolver; import com.xxxx.admin.support.config.BaseMvcConfig; @EnableWebMvc @ComponentScan( basePackages = { "com.xxxx.cms.admin.config.advice", "com.xxxx.cms.admin.controller", "com.xxxx.cms.admin.rest.controller" }, includeFilters = { @ComponentScan.Filter(value = Component.class), @ComponentScan.Filter(value = Controller.class) } ) public class MvcConfig extends BaseMvcConfig { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); registry.addResourceHandler("/static/upload/public/feedback/**").addResourceLocations("/static/upload/public/feedback/"); } @Bean public XmlViewResolver xmlViewResolver() { XmlViewResolver xmlViewResolver = new XmlViewResolver(); Resource resource = new ClassPathResource("/hs-cms-admin-config/spring-views.xml"); xmlViewResolver.setLocation(resource); xmlViewResolver.setOrder(1); return xmlViewResolver; } }
import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.context.annotation.Import; import org.springframework.format.FormatterRegistry; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.http.converter.ByteArrayHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.client.RestTemplate; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; import com.xxxx.admin.support.config.resolver.BaseDefaultHandlerExceptionResolver; import com.xxxx.admin.support.config.shiro.ShiroConfig; import com.xxxx.admin.support.converter.IntegerToBaseTypeConverterFactory; import com.xxxx.admin.support.converter.IntegerToIBaseTypeConverterFactory; import com.xxxx.admin.support.converter.StringToBaseTypeConverterFactory; import com.xxxx.admin.support.converter.StringToCalendar; import com.xxxx.admin.support.converter.StringToIBaseTypeConverterFactory; import com.xxxx.admin.support.converter.StringToLocalDate; import com.xxxx.admin.support.converter.StringToLocalDateTime; import com.xxxx.admin.support.converter.StringToLocalTime; @Configuration @EnableWebMvc @EnableAspectJAutoProxy(proxyTargetClass = true) @Import({ ShiroConfig.class }) public abstract class BaseMvcConfig extends WebMvcConfigurerAdapter { private static final Logger logger = LoggerFactory.getLogger(BaseMvcConfig.class); // @Bean // public RefererInterceptor refererInterceptor() { // return new RefererInterceptor(); // } // // @Bean // public SellChannelInterceptor sellChannelInterceptor() { // return new SellChannelInterceptor(); // } // // @Bean // public AutoLoginInterceptor autoLoginInterceptor() { // return new AutoLoginInterceptor(); // } // // @Bean // public AuthCheckInterceptor authCheckInterceptor() { // return new AuthCheckInterceptor(); // } // @Override // public void addInterceptors(InterceptorRegistry registry) { // registry // .addInterceptor(refererInterceptor()) // .addPathPatterns("/**"); // registry // .addInterceptor(sellChannelInterceptor()) // .addPathPatterns("/**"); // registry // .addInterceptor(autoLoginInterceptor()) // .addPathPatterns("/**"); //// registry //// .addInterceptor(new ErrorHandlerInterceptor()) //// .addPathPatterns("/**"); // } @Override public void addFormatters(FormatterRegistry registry) { registry.addConverter(new StringToLocalDate()); registry.addConverter(new StringToLocalDateTime()); registry.addConverter(new StringToCalendar()); registry.addConverter(new StringToLocalTime()); registry.addConverterFactory(new StringToBaseTypeConverterFactory()); registry.addConverterFactory(new IntegerToBaseTypeConverterFactory()); registry.addConverterFactory(new StringToIBaseTypeConverterFactory()); registry.addConverterFactory(new IntegerToIBaseTypeConverterFactory()); } @Bean public InternalResourceViewResolver jstlViewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.class); viewResolver.setPrefix("/WEB-INF/views/"); viewResolver.setSuffix(".jsp"); viewResolver.setOrder(2); return viewResolver; } @Override public void configureMessageConverters( List<HttpMessageConverter<?>> converters ) { converters.add(jackson2Converter()); converters.add(new ByteArrayHttpMessageConverter()); } @Bean public MappingJackson2HttpMessageConverter jackson2Converter() { MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); ObjectMapper objectMapper = new ObjectMapper(); // objectMapper.findAndRegisterModules(); JavaTimeModule javaTimeModule = new JavaTimeModule(); // Hack time module to allow 'Z' at the end of string (i.e. javascript json's) DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(dtf)); // javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(dtf)); objectMapper.registerModule(javaTimeModule); // objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); objectMapper.setDateFormat(sdf); converter.setObjectMapper(objectMapper); return converter; } @Bean public CommonsMultipartResolver multipartResolver() { CommonsMultipartResolver resolver = new CommonsMultipartResolver(); resolver.setMaxUploadSize(50000000); resolver.setDefaultEncoding("UTF-8"); return resolver; } // @Override // public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) { // exceptionResolvers.add(ajaxHandlerExceptionResolver()); // } // // @Bean // public HandlerExceptionResolver ajaxHandlerExceptionResolver() { // AjaxHandlerExceptionResolver resolver = new AjaxHandlerExceptionResolver(); // return resolver; // } @Override public void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) { Integer index = null; int size = exceptionResolvers.size(); for (int i = 0; i < size; i++) { if (exceptionResolvers.get(i) instanceof DefaultHandlerExceptionResolver) { logger.info("Find DefaultHandlerExceptionResolver [{}]", i); index = i; break; } } if (index != null) { logger.info("Replace DefaultHandlerExceptionResolver [{}]", index); exceptionResolvers.set(index, new BaseDefaultHandlerExceptionResolver()); } else { logger.info("Add BaseDefaultHandlerExceptionResolver"); exceptionResolvers.add(new BaseDefaultHandlerExceptionResolver()); } } @Bean public RestTemplate restTemplate() { HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(); clientHttpRequestFactory.setConnectTimeout(5000); RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory); return restTemplate; } }
import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import javax.servlet.Filter; import org.apache.shiro.mgt.CachingSecurityManager; import org.apache.shiro.spring.LifecycleBeanPostProcessor; import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; import org.springframework.core.env.Environment; import org.springframework.data.redis.cache.DefaultRedisCachePrefix; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.cache.RedisCachePrefix; import org.springframework.data.redis.core.RedisTemplate; @Configuration public class ShiroConfig { private static final Logger logger = LoggerFactory.getLogger(ShiroConfig.class); @Autowired private Environment env; @Autowired @Qualifier("shiroRedisTemplate") private RedisTemplate<?, ?> redisTemplate; @Bean public ShiroRealm shiroRealm() { return new ShiroRealm(); } @Bean public AjaxUserFilter ajaxUserFilter() { return new AjaxUserFilter(); } /** * shiro核心安全管理类 * @return */ @Bean public CachingSecurityManager securityManager() { logger.info("Shiro redis cache manager init"); RedisCachePrefix cachePrefix = new DefaultRedisCachePrefix(); cachePrefix.prefix("hs:admin:shiro"); RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate); redisCacheManager.setUsePrefix(true); redisCacheManager.setCachePrefix(cachePrefix); // 30min redisCacheManager.setDefaultExpiration(60 * 30); ShiroCacheManager cacheManager = new ShiroCacheManager(); cacheManager.setCacheManger(redisCacheManager); logger.info("Shiro security manager init"); CachingSecurityManager securityManager = new DefaultWebSecurityManager(shiroRealm()); securityManager.setCacheManager(cacheManager); return securityManager; } @Bean public ShiroFilterFactoryBean shiroFilter() { logger.info("Shiro filter factory bean manager init"); ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean(); // 必须设置 SecurityManager shiroFilter.setSecurityManager(securityManager()); // 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面 shiroFilter.setLoginUrl(env.getProperty("hs.admin.support.path.login", "https://admin.xxxx.com/login")); // 登录成功后要跳转的链接 shiroFilter.setSuccessUrl("/"); // 未授权界面; // factoryBean.setUnauthorizedUrl("/403"); // 拦截器 Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>(); // 静态资源允许访问 filterChainDefinitionMap.put("/resources/**", "anon"); // 登录页允许访问 filterChainDefinitionMap.put("/captcha.jpg", "anon"); filterChainDefinitionMap.put("/login", "anon"); filterChainDefinitionMap.put("/third-login/**", "anon"); filterChainDefinitionMap.put("/hsapi/**", "anon"); // 其他资源需要认证 filterChainDefinitionMap.put("/**", "user, authc"); shiroFilter.setFilterChainDefinitionMap(filterChainDefinitionMap); Map<String, Filter> filters = new HashMap<String, Filter>(1); filters.put("user", ajaxUserFilter()); shiroFilter.setFilters(filters); return shiroFilter; } @Bean public static LifecycleBeanPostProcessor lifecycleBeanPostProcessor() { return new LifecycleBeanPostProcessor(); } @Bean @DependsOn("lifecycleBeanPostProcessor") public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() { DefaultAdvisorAutoProxyCreator creator = new DefaultAdvisorAutoProxyCreator(); creator.setProxyTargetClass(true); return creator; } /** * 开启 SHIRO AOP 注解支持<br> * 使用代理方式 所以需要开启代码支持<br/> * 拦截 @RequiresPermissions 注释的方法 * @return */ @Bean @DependsOn("lifecycleBeanPostProcessor") public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() { logger.info("Shiro authorizaion attribute source advisor init"); AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor(); advisor.setSecurityManager(securityManager()); return advisor; } }
import java.util.Collection; import java.util.Set; import org.apache.shiro.cache.Cache; import org.apache.shiro.cache.CacheException; import org.apache.shiro.cache.CacheManager; import org.springframework.cache.support.SimpleValueWrapper; public class ShiroCacheManager implements CacheManager { private org.springframework.cache.CacheManager cacheManager; public org.springframework.cache.CacheManager getCacheManager() { return cacheManager; } public void setCacheManger(org.springframework.cache.CacheManager cacheManager) { this.cacheManager = cacheManager; } @Override public <K, V> Cache<K, V> getCache(String name) throws CacheException { org.springframework.cache.Cache cache = getCacheManager().getCache(name); return new CacheWrapper<K, V>(cache); } private class CacheWrapper<K, V> implements Cache<K, V> { private org.springframework.cache.Cache cache; public CacheWrapper(org.springframework.cache.Cache cache) { this.cache = cache; } @SuppressWarnings("unchecked") @Override public V get(K key) throws CacheException { Object value = cache.get(key); if (value instanceof SimpleValueWrapper) { return (V) ((SimpleValueWrapper) value).get(); } return (V) value; } @Override public V put(K key, V value) throws CacheException { cache.put(key, value); return value; } @SuppressWarnings("unchecked") @Override public V remove(K key) throws CacheException { Object value = get(key); cache.evict(key); return (V) value; } @Override public void clear() throws CacheException { cache.clear(); } @Override public int size() { throw new UnsupportedOperationException("invoke spring cache abstract size method not supported"); } @Override public Set<K> keys() { throw new UnsupportedOperationException("invoke spring cache abstract keys method not supported"); } @Override public Collection<V> values() { throw new UnsupportedOperationException("invoke spring cache abstract values method not supported"); } } }
import java.time.LocalDate; import org.apache.commons.lang3.StringUtils; import org.springframework.core.convert.converter.Converter; public class StringToLocalDate implements Converter<String, LocalDate> { @Override public LocalDate convert(String arg0) { if (StringUtils.isBlank(arg0)) { return null; } LocalDate ld = null; try { ld = LocalDate.parse(arg0); } catch (Exception e) { e.printStackTrace(); } return ld; } }
import org.apache.commons.lang3.StringUtils; import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.ConverterFactory; import com.xxxx.support.constant.BaseType; public class StringToBaseTypeConverterFactory implements ConverterFactory<String, BaseType> { @Override public <T extends BaseType> Converter<String, T> getConverter(Class<T> arg0) { return new StringToBaseType<T>(arg0); } private class StringToBaseType<T extends BaseType> implements Converter<String, T> { private final Class<T> type; public StringToBaseType(Class<T> type) { this.type = type; } public T convert(String source) { if (StringUtils.isBlank(source)) { // It's an empty enum identifier: reset the enum value to null. return null; } return (T) BaseType.valueOf(this.type, source.trim()); } } }
上一篇: oracle 同一表中父类关联子类