下面列出了怎么用org.springframework.context.annotation.Primary的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 注意,自定义TokenServices的时候,需要设置@Primary,否则报错
*/
@Primary
@Bean
public DefaultTokenServices defaultTokenServices() {
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setTokenStore(tokenStore());
tokenServices.setSupportRefreshToken(true);
// 这里如果设置为false则不能更新refresh_token,如果需要刷新token的功能需要设置成true
tokenServices.setSupportRefreshToken(true);
// 设置上次RefreshToken是否还可以使用 默认为true
tokenServices.setReuseRefreshToken(false);
// token有效期自定义设置,默认12小时
tokenServices.setAccessTokenValiditySeconds(60 * 60 * 6);
// refresh_token默认30天
tokenServices.setRefreshTokenValiditySeconds(60 * 60 * 8);
tokenServices.setTokenEnhancer(tokenEnhancer());
return tokenServices;
}
@Primary
@Bean("redisTemplate")
// 没有此属性就不会装配bean 如果是单个redis 将此注解注释掉
@ConditionalOnProperty(name = "spring.redis.cluster.nodes", matchIfMissing = false)
public RedisTemplate<String, Object> getRedisTemplate() {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
redisTemplate.setConnectionFactory(lettuceConnectionFactory);
RedisSerializer stringSerializer = new StringRedisSerializer();
// RedisSerializer redisObjectSerializer = new RedisObjectSerializer();
RedisSerializer redisObjectSerializer = new RedisObjectSerializer();
redisTemplate.setKeySerializer(stringSerializer); // key的序列化类型
redisTemplate.setHashKeySerializer(stringSerializer);
redisTemplate.setValueSerializer(redisObjectSerializer); // value的序列化类型
redisTemplate.setHashValueSerializer(redisObjectSerializer); // value的序列化类型
redisTemplate.afterPropertiesSet();
redisTemplate.opsForValue().set("hello", "wolrd");
return redisTemplate;
}
@Override
@Bean
@Primary
public CacheManager cacheManager() {
final RedisCacheWriter redisCacheWriter =
RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory);
final RedisCacheConfiguration defaultCacheConfig =
RedisCacheConfiguration.defaultCacheConfig()
// 不缓存 null 值
.disableCachingNullValues()
// 使用注解时的序列化、反序列化对
.serializeKeysWith(stringPair)
.serializeValuesWith(jacksonPair)
.prefixKeysWith("syhthems:cache:");
return new RedisCacheManager(redisCacheWriter, defaultCacheConfig);
}
@Bean
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
// 通过该方法对mapper对象进行设置,所有序列化的对象都将按改规则进行系列化
// Include.Include.ALWAYS 默认
// Include.NON_DEFAULT 属性为默认值不序列化
// Include.NON_EMPTY 属性为 空("") 或者为 NULL 都不序列化,则返回的json是没有这个字段的。这样对移动端会更省流量
// Include.NON_NULL 属性为NULL 不序列化,就是为null的字段不参加序列化
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
// 字段保留,将null值转为""
// objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>()
// {
// @Override
// public void serialize(Object o, JsonGenerator jsonGenerator,
// SerializerProvider serializerProvider)
// throws IOException, JsonProcessingException
// {
// jsonGenerator.writeString("");
// }
// });
return objectMapper;
}
@Bean
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
// 通过该方法对mapper对象进行设置,所有序列化的对象都将按改规则进行系列化
// Include.Include.ALWAYS 默认
// Include.NON_DEFAULT 属性为默认值不序列化
// Include.NON_EMPTY 属性为 空("") 或者为 NULL 都不序列化,则返回的json是没有这个字段的。这样对移动端会更省流量
// Include.NON_NULL 属性为NULL 不序列化,就是为null的字段不参加序列化
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
// 字段保留,将null值转为""
// objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>()
// {
// @Override
// public void serialize(Object o, JsonGenerator jsonGenerator,
// SerializerProvider serializerProvider)
// throws IOException, JsonProcessingException
// {
// jsonGenerator.writeString("");
// }
// });
return objectMapper;
}
@Bean
@Primary
public Pay pay() {
// 微信
if (wxPayProperties.isEnabled()) {
if (!ClassLoaderUtil.isPresent("com.egzosn.pay.wx.api.WxPayService")) {
log.error("【支付配置】未引入依赖模块:pay-java-wx");
}
wxPay();
}
// 支付宝
if (aliPayProperties.isEnabled()) {
if (!ClassLoaderUtil.isPresent("com.egzosn.pay.ali.api.AliPayService")) {
log.error("【支付配置】未引入依赖模块:pay-java-ali");
}
aliPay();
}
// Bean
return new Pay(payServiceMap);
}
@Bean(name = "primarySqlSessionFactory")
@Primary
public SqlSessionFactory sqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource) throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setTypeAliasesPackage(TYPE_ALIASES_Package);
PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + MAPPER_PATH;
//添加插件
sessionFactory.setPlugins(pageInterceptor());
sessionFactory.setDataSource(dataSource);
sessionFactory.setMapperLocations(pathMatchingResourcePatternResolver.getResources(packageSearchPath));
sessionFactory.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
return sessionFactory.getObject();
}
@Bean //声明其为Bean实例
@Primary //在同样的DataSource中,首先使用被标注的DataSource
public DataSource dataSource() {
DruidDataSource datasource = new DruidDataSource();
logger.info("dbUrl--------" + dbUrl);
datasource.setUrl(this.dbUrl);
datasource.setUsername(username);
datasource.setPassword(password);
datasource.setDriverClassName(driverClassName);
//configuration
datasource.setInitialSize(initialSize);
datasource.setMinIdle(minIdle);
datasource.setMaxActive(maxActive);
datasource.setMaxWait(maxWait);
datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setValidationQuery(validationQuery);
datasource.setTestWhileIdle(testWhileIdle);
datasource.setTestOnBorrow(testOnBorrow);
datasource.setTestOnReturn(testOnReturn);
datasource.setPoolPreparedStatements(poolPreparedStatements);
datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
try {
datasource.setFilters(filters);
} catch (SQLException e) {
logger.error("druid configuration initialization filter", e);
}
datasource.setConnectionProperties(connectionProperties);
return datasource;
}
@Bean
@Primary
@ConditionalOnSingleCandidate(JdbcTemplate.class)
@ConditionalOnMissingBean(NamedParameterJdbcOperations.class)
public NamedParameterJdbcTemplate namedParameterJdbcTemplate(JdbcTemplate jdbcTemplate) {
return new NamedParameterJdbcTemplate(jdbcTemplate);
}
@Primary
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public ErrorWebExceptionHandler errorWebExceptionHandler(ObjectProvider<List<ViewResolver>> viewResolversProvider,
ServerCodecConfigurer serverCodecConfigurer) {
ExceptionHandle jsonExceptionHandler = new ExceptionHandle();
jsonExceptionHandler.setViewResolvers(viewResolversProvider.getIfAvailable(Collections::emptyList));
jsonExceptionHandler.setMessageWriters(serverCodecConfigurer.getWriters());
jsonExceptionHandler.setMessageReaders(serverCodecConfigurer.getReaders());
return jsonExceptionHandler;
}
@Bean
@Primary
@LoadBalanced
public RestTemplate lbRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
@Override
public void handleError(ClientHttpResponse response) throws IOException {
if (response.getRawStatusCode() != HttpStatus.BAD_REQUEST.value()) {
super.handleError(response);
}
}
});
return restTemplate;
}
@Bean
@Primary
public DefaultTokenServices tokenServices() {
DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setTokenStore(tokenStore());
return defaultTokenServices;
}
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
// 配置数据源(注意,我使用的是 HikariCP 连接池),以上注解是指定数据源,否则会有冲突
return DataSourceBuilder.create().build();
}
/**
* Hal provider data rest hal provider.
*
* @param repositoryRestConfiguration the repository rest configuration
* @return the data rest hal provider
*/
@Bean
@ConditionalOnMissingBean
@Primary
@Lazy(false)
DataRestHalProvider halProvider(Optional<RepositoryRestConfiguration> repositoryRestConfiguration) {
return new DataRestHalProvider(repositoryRestConfiguration);
}
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
// 配置数据源(注意,我使用的是 HikariCP 连接池),以上注解是指定数据源,否则会有冲突
return DataSourceBuilder.create().build();
}
@Bean
@Primary
public Keeper initKeeper(Keeper keeper, StringRedisTemplate stringRedisTemplate) {
keeper.setSubjectType(SubjectType.SESSION);
// keeper.setAuthenticInfoCache(new AuthenticRedisCache(stringRedisTemplate));
keeper.setKeeperCache(new RedisCache<>(stringRedisTemplate));
return keeper;
}
@Bean
@Primary
public Keeper initKeeper(Keeper keeper, StringRedisTemplate stringRedisTemplate) {
keeper.setSubjectType(SubjectType.JWT);
// keeper.setAuthenticInfoCache(new AuthenticRedisCache(stringRedisTemplate));
keeper.setKeeperCache(new RedisCache<>(stringRedisTemplate));
return keeper;
}
@Bean(name = "dynamicDataSource")
@Primary
public DynamicDataSource dataSource(DataSource masterDataSource, DataSource slaveDataSource)
{
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource);
targetDataSources.put(DataSourceType.SLAVE.name(), slaveDataSource);
return new DynamicDataSource(masterDataSource, targetDataSources);
}
@Bean
@Primary
DomainEvents domainEventsWithStorage(ApplicationEventPublisher applicationEventPublisher, MeterRegistry meterRegistry) {
return new StoreAndForwardDomainEventPublisher(
new MeteredDomainEventPublisher(
new JustForwardDomainEventPublisher(applicationEventPublisher), meterRegistry),
new InMemoryEventsStorage()
);
}
@Bean
@Primary
public DefaultTokenServices defaultTokenServices() {
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setTokenStore(tokenStore());
tokenServices.setSupportRefreshToken(true);
tokenServices.setClientDetailsService(redisClientDetailsService);
return tokenServices;
}
@Bean //声明其为Bean实例
@Primary //在同样的DataSource中,首先使用被标注的DataSource
public DataSource dataSource() {
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(url);
datasource.setUsername(username);
datasource.setPassword(password);
datasource.setDriverClassName(driverClassName);
//configuration
datasource.setInitialSize(initialSize);
datasource.setMinIdle(minIdle);
datasource.setMaxActive(maxActive);
datasource.setMaxWait(maxWait);
datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setValidationQuery(validationQuery);
datasource.setTestWhileIdle(testWhileIdle);
datasource.setTestOnBorrow(testOnBorrow);
datasource.setTestOnReturn(testOnReturn);
datasource.setPoolPreparedStatements(poolPreparedStatements);
datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
try {
datasource.setFilters(filters);
} catch (SQLException e) {
logger.error("druid configuration initialization filter: " + e);
}
datasource.setConnectionProperties(connectionProperties);
logger.debug("druid configuration datasource 成功" + datasource);
logger.debug("druid configuration datasource 成功" + name);
return datasource;
}
@Bean(name = "mysqlSessionFactory")
@Primary
public SqlSessionFactory sqlSessionFactory(@Qualifier("mysqlDataSource") DataSource dataSource,SoaConfig soaConfig) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setPlugins(new Interceptor[] {new CatMybatisPlugin(soaConfig)});
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_XML_PATH));
bean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
return bean.getObject();
}
/**
* Jackson全局配置
*
* @param properties
* @return
*/
@Bean
@Primary
public JacksonProperties jacksonProperties(JacksonProperties properties) {
properties.setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL);
properties.getSerialization().put(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
properties.setDateFormat("yyyy-MM-dd HH:mm:ss");
properties.setTimeZone(TimeZone.getTimeZone("GMT+8"));
log.info("JacksonProperties [{}]", properties);
return properties;
}
@Primary
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
//对象的序列化
RedisSerializationContext.SerializationPair valueSerializationPair
= RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer());
//全局redis缓存过期时间
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofDays(1))
// .serializeKeysWith()
.serializeValuesWith(valueSerializationPair);
return new RedisCacheManager(RedisCacheWriter.nonLockingRedisCacheWriter(factory), redisCacheConfiguration);
}
@Bean(name = "inMemoryDbDataSource")
@Primary
public DataSource inMemoryDbDataSource() {
// DataSource dataSource = new DruidDataSource();
// return dataSource;
return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2)
.addScript("classpath:sql/schema.sql").build();
}
@Bean
@Primary
// @ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"));
// objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return objectMapper;
}
@Bean
@Primary
JedisConnectionFactory jedisConnectionFactory() {
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration ();
redisStandaloneConfiguration.setHostName(redisProperties.getHost());
redisStandaloneConfiguration.setPort(redisProperties.getPort());
redisStandaloneConfiguration.setPassword(RedisPassword.of(redisProperties.getPassword()));
redisStandaloneConfiguration.setDatabase(RedisDbIndexConst.DB_INDEX_DEFAULT);
JedisClientConfiguration.JedisClientConfigurationBuilder jedisClientConfiguration = JedisClientConfiguration.builder();
JedisConnectionFactory factory = new JedisConnectionFactory(redisStandaloneConfiguration,
jedisClientConfiguration.usePooling().poolConfig(jedisPoolConfig()).build());
return factory;
}
@Bean
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
// 排序key
objectMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
//忽略空bean转json错误
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
//忽略在json字符串中存在,在java类中不存在字段,防止错误。
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
/**
* 序列换成json时,将所有的long变成string
* 因为js中得数字类型不能包含所有的java long值
*/
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
// 兼容fastJson 的一些空值处理
SerializerFeature[] features = new SerializerFeature[]{
WriteNullListAsEmpty,
WriteNullStringAsEmpty,
WriteNullNumberAsZero,
WriteNullBooleanAsFalse,
WriteNullMapAsEmpty
};
objectMapper.setSerializerFactory(objectMapper.getSerializerFactory().withSerializerModifier(new FastJsonSerializerFeatureCompatibleForJackson(features)));
log.info("ObjectMapper [{}]", objectMapper);
return objectMapper;
}
@Bean
@Primary
public DefaultTokenServices tokenServices() {
DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setTokenStore(jwtTokenStore());
defaultTokenServices.setSupportRefreshToken(true);
return defaultTokenServices;
}
@Test
public void primaryMetadataIsPropagated() {
@Configuration class Config {
@Primary @Bean
Object foo() { return null; }
}
assertTrue("primary metadata was not propagated",
beanDef(Config.class).isPrimary());
}