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());
}
}
}
分享到:
相关推荐
本项目示例基于spring boot 最新版本(2.1.9)实现,Spring Boot、Spring Cloud 学习示例,将持续更新…… 在基于Spring Boot、Spring Cloud 分布微服务开发过程中,根据实际项目环境,需要选择、集成符合项目...
这个"spring的Java项目"很可能是为了展示Spring框架的基础用法,帮助开发者理解和掌握Spring的核心概念。下面将详细解释Spring框架的一些关键知识点。 1. **IoC(Inversion of Control)控制反转**:Spring通过IoC...
本示例将详细介绍如何使用注解配置实现Spring框架的注入。 首先,我们需要了解几个关键的注解: 1. `@Component`:这是Spring中的基础组件注解,可以标记一个类为Spring管理的bean。例如,我们可以定义一个简单的...
Java EE是企业级应用开发的重要框架,而"精通Java EE项目案例-基于Eclipse Spring Struts Hibernate光盘源码"的资源提供了丰富的实践学习材料,旨在帮助开发者深入了解和掌握Java后端开发技术。这个项目案例涵盖了四...
在本示例中,我们将探讨如何使用Java Spring Boot框架来实现一个基于RAG(Red-Amber-Green)架构的GenAI项目。RAG是一种广泛应用于项目管理、风险评估和KPI跟踪的颜色编码系统,其中Red代表高风险或问题,Amber表示...
Java Spring框架是一个广泛...以上就是基于Java Spring框架的“待办事项”管理应用程序中涉及的主要知识点。通过学习和实践这个示例,开发者可以深入了解Spring框架如何在实际项目中发挥作用,提升开发效率和应用质量。
在本示例中,我们探讨的是一个基于纯Java配置的Spring MVC项目。Spring MVC是Spring框架的一个重要模块,专门用于构建Web应用程序。它提供了一种模型-视图-控制器(MVC)架构,使得开发人员可以更有效地组织和管理...
【标题】"maven spring mvc示例源码"揭示了这是一个基于Maven构建的Spring MVC Java项目的实例。Spring MVC是Spring框架的一部分,用于构建Web应用程序,而Maven则是一个项目管理和综合工具,用于自动化构建、依赖...
spring-javaconfig-sample, Spring MVC/Spring Data JPA/Hibernate的spring JavaConfig示例 spring-配置示例自 spring 3.0以来,JavaConfig特性被包含在核心 spring 模块中。 因此Java开发人员可以将 spring bean...
本项目为基于Java语言的Spring框架设计的示例源码,包含37个文件,包括26个Java源文件、8个XML配置文件、1个Git忽略文件、1个Protocol Buffers文件以及1个Markdown文件。
在本文中,我们将深入探讨`spring_mongo`项目示例,这是一个基于Spring框架集成MongoDB数据库的应用程序实例。MongoDB是一个流行的NoSQL数据库,它以JSON格式存储数据,适合处理大规模、非结构化或半结构化数据。而...
本项目是基于SpringCloud开发的微服务架构示例项目,包含749个文件,其中包括126个Java源代码文件、108个HTML文件、105个JavaScript脚本文件、79个JSP页面文件、78个Freemarker模板文件、63个CSS样式表文件、51个JPG...
在压缩包`spring_mvc_01`中,可能包含了基本的Spring MVC项目结构,如`web.xml`配置文件、Spring MVC配置类、控制器类以及简单的JSP视图。通过分析这些文件,你可以更直观地学习如何配置和运行一个基本的Spring MVC...
在本文中,我们将深入探讨如何使用Spring MVC和Maven来构建一个Java项目。Spring MVC是Spring框架的一个模块,专门用于构建Web应用程序,而Maven则是一个项目管理工具,用于简化构建、依赖管理和项目文档的生成。 *...
6. **配置文件**:通常,这些配置会在Spring Batch的XML或Java配置文件中定义,包括Job、Step、Partitioner、TaskExecutor以及其他相关组件的设置。 在这个示例中,我们可能会看到如何通过XML或Java配置实现上述...
本文将深入探讨Spring Boot基于Java的容器配置,通过示例代码帮助理解其工作原理和使用方法。 首先,Spring容器是Spring框架的核心,它负责管理对象的生命周期,包括创建、初始化、装配和销毁。Spring提供了多种...
SpringCloud是中国Java开发者广泛使用的微服务框架之一,它基于Netflix OSS构建,提供了众多服务治理功能,如服务发现、负载均衡、断路器、配置中心、API Gateway等,旨在简化分布式系统开发。本压缩包文件“Spring...
首先,我们需要在Spring项目中配置BlazeDS。这包括在`web.xml`中添加BlazeDS的Servlet和监听器配置,以及在Spring配置文件中定义服务代理。这样,Spring的服务可以通过HTTP或AMF(Action Message Format)协议被Flex...
本示例将探讨如何在Spring框架中配置最基础的Web服务,特别关注的是基于CXF的Web服务。CXF是一个强大的开源框架,它支持SOAP和RESTful风格的Web服务,使得开发者能够方便地创建和消费Web服务。 首先,我们需要理解...