org.springframework.context.annotation.Primary Java Examples

The following examples show how to use org.springframework.context.annotation.Primary. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JacksonConfig.java    From xmall with MIT License 7 votes vote down vote up
@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;
    }
 
Example #2
Source File: RedisConfig.java    From open-capacity-platform with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #3
Source File: RedisCacheConfig.java    From syhthems-platform with MIT License 6 votes vote down vote up
@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);
}
 
Example #4
Source File: SophiaAuthorizationServerConfig.java    From sophia_scaffolding with Apache License 2.0 6 votes vote down vote up
/**
 * 注意,自定义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;
}
 
Example #5
Source File: PayAutoConfig.java    From yue-library with Apache License 2.0 6 votes vote down vote up
@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);
   }
 
Example #6
Source File: JacksonConfig.java    From mall-swarm with Apache License 2.0 6 votes vote down vote up
@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;
    }
 
Example #7
Source File: DataSourceConfig.java    From momo-cloud-permission with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #8
Source File: BaseResourceServerConfigurerAdapter.java    From smaker with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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;
}
 
Example #9
Source File: OAuth2AuthorizationServerConfig.java    From gemini with Apache License 2.0 5 votes vote down vote up
@Bean
@Primary
public DefaultTokenServices tokenServices() {
    DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
    defaultTokenServices.setTokenStore(tokenStore());
    return defaultTokenServices;
}
 
Example #10
Source File: DruidConfig.java    From codeway_service with GNU General Public License v3.0 5 votes vote down vote up
@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;
}
 
Example #11
Source File: GatewayApplication.java    From microservice-recruit with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #12
Source File: JdbcTemplateAutoConfiguration.java    From sqlhelper with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Bean
@Primary
@ConditionalOnSingleCandidate(JdbcTemplate.class)
@ConditionalOnMissingBean(NamedParameterJdbcOperations.class)
public NamedParameterJdbcTemplate namedParameterJdbcTemplate(JdbcTemplate jdbcTemplate) {
    return new NamedParameterJdbcTemplate(jdbcTemplate);
}
 
Example #13
Source File: GroupDocConfiguration.java    From tools with MIT License 5 votes vote down vote up
@Bean
@Primary
@ConditionalOnMissingBean
public DocGroupHandler swaggerResourceHandler(DocGroup docGroup) {
    switch (docGroup.getType()) {
        case URL:
            return new DefaultUrlGroupDocHandler();
        case NAME:
            return new DefaultNameGroupDocHandler();
        default:
            throw new IllegalArgumentException("Cannot found your doc handler");
    }
}
 
Example #14
Source File: KeeperBeanConfig.java    From keeper with Apache License 2.0 5 votes vote down vote up
@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;
    }
 
Example #15
Source File: AuthServiceAutoConfig.java    From yue-library with Apache License 2.0 5 votes vote down vote up
@Bean
@Primary
@ConditionalOnBean(Redis.class)
public User user() {
	log.info("【初始化配置-AuthService-User客户端】配置项:" + AuthServiceProperties.PREFIX + "。Bean:User ... 已初始化完毕。");
	return new User();
}
 
Example #16
Source File: KeeperBeanConfig.java    From keeper with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #17
Source File: BeanAnnotationAttributePropagationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void primaryMetadataIsPropagated() {
	@Configuration class Config {
		@Primary @Bean
		Object foo() { return null; }
	}

	assertTrue("primary metadata was not propagated",
			beanDef(Config.class).isPrimary());
}
 
Example #18
Source File: PrimaryConfig.java    From txle with Apache License 2.0 5 votes vote down vote up
@Primary
@Bean(name = "primaryEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(@Qualifier("primaryDataSource") DataSource primaryDataSource, EntityManagerFactoryBuilder builder) {
    return builder.dataSource(primaryDataSource)
            .properties(jpaProperties.getProperties())
            .packages("com.actionsky.txle.grpc.entity")
            .persistenceUnit("primaryPersistenceUnit")
            .build();
}
 
Example #19
Source File: DruidConfig.java    From feiqu-opensource with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #20
Source File: DomainEventsTestConfig.java    From library with MIT License 5 votes vote down vote up
@Bean
@Primary
DomainEvents domainEventsWithStorage(ApplicationEventPublisher applicationEventPublisher, MeterRegistry meterRegistry) {
    return new StoreAndForwardDomainEventPublisher(
            new MeteredDomainEventPublisher(
                    new JustForwardDomainEventPublisher(applicationEventPublisher), meterRegistry),
            new InMemoryEventsStorage()
    );
}
 
Example #21
Source File: FebsAuthorizationServerConfigure.java    From FEBS-Cloud with Apache License 2.0 5 votes vote down vote up
@Bean
@Primary
public DefaultTokenServices defaultTokenServices() {
    DefaultTokenServices tokenServices = new DefaultTokenServices();

    tokenServices.setTokenStore(tokenStore());
    tokenServices.setSupportRefreshToken(true);
    tokenServices.setClientDetailsService(redisClientDetailsService);
    return tokenServices;
}
 
Example #22
Source File: DruidConfig.java    From sophia_scaffolding with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #23
Source File: MySqlDatasourceConfiguration.java    From pmq with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #24
Source File: ApiConfiguration.java    From open-cloud with MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example #25
Source File: RedisConfig.java    From kvf-admin with MIT License 5 votes vote down vote up
@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);
    }
 
Example #26
Source File: InMemoryDbDatasourceConfiguration.java    From pmq with Apache License 2.0 5 votes vote down vote up
@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();
    }
 
Example #27
Source File: AuthorizationServerConfig.java    From syhthems-platform with MIT License 5 votes vote down vote up
@Bean
@Primary
public DefaultTokenServices tokenServices() {
    DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
    defaultTokenServices.setTokenStore(jwtTokenStore());
    defaultTokenServices.setSupportRefreshToken(true);
    return defaultTokenServices;
}
 
Example #28
Source File: MqConfig.java    From pmq with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #29
Source File: RedisConfig.java    From charging_pile_cloud with MIT License 5 votes vote down vote up
@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;
}
 
Example #30
Source File: JacksonAutoConfiguration.java    From open-cloud with MIT License 5 votes vote down vote up
@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;
}