Java Code Examples for org.springframework.context.annotation.Primary

The following examples show how to use org.springframework.context.annotation.Primary. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
/**
 * 注意,自定义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 2
Source Project: open-capacity-platform   Source File: RedisConfig.java    License: 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 Project: syhthems-platform   Source File: RedisCacheConfig.java    License: 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 Project: mall-swarm   Source File: JacksonConfig.java    License: 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 5
Source Project: xmall   Source File: JacksonConfig.java    License: MIT License 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 6
Source Project: yue-library   Source File: PayAutoConfig.java    License: 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 7
Source Project: momo-cloud-permission   Source File: DataSourceConfig.java    License: 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 Project: codeway_service   Source File: DruidConfig.java    License: 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 9
@Bean
@Primary
@ConditionalOnSingleCandidate(JdbcTemplate.class)
@ConditionalOnMissingBean(NamedParameterJdbcOperations.class)
public NamedParameterJdbcTemplate namedParameterJdbcTemplate(JdbcTemplate jdbcTemplate) {
    return new NamedParameterJdbcTemplate(jdbcTemplate);
}
 
Example 10
Source Project: microservice-recruit   Source File: GatewayApplication.java    License: 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 11
@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 12
Source Project: gemini   Source File: OAuth2AuthorizationServerConfig.java    License: 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 13
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
    // 配置数据源(注意,我使用的是 HikariCP 连接池),以上注解是指定数据源,否则会有冲突
    return DataSourceBuilder.create().build();
}
 
Example 14
/**
 * 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);
}
 
Example 15
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
    // 配置数据源(注意,我使用的是 HikariCP 连接池),以上注解是指定数据源,否则会有冲突
    return DataSourceBuilder.create().build();
}
 
Example 16
Source Project: keeper   Source File: KeeperBeanConfig.java    License: 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 17
Source Project: keeper   Source File: KeeperBeanConfig.java    License: 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 18
Source Project: feiqu-opensource   Source File: DruidConfig.java    License: 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 19
Source Project: library   Source File: DomainEventsTestConfig.java    License: 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 20
@Bean
@Primary
public DefaultTokenServices defaultTokenServices() {
    DefaultTokenServices tokenServices = new DefaultTokenServices();

    tokenServices.setTokenStore(tokenStore());
    tokenServices.setSupportRefreshToken(true);
    tokenServices.setClientDetailsService(redisClientDetailsService);
    return tokenServices;
}
 
Example 21
Source Project: sophia_scaffolding   Source File: DruidConfig.java    License: 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 22
Source Project: pmq   Source File: MySqlDatasourceConfiguration.java    License: 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 23
Source Project: open-cloud   Source File: ApiConfiguration.java    License: 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 24
Source Project: kvf-admin   Source File: RedisConfig.java    License: 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 25
Source Project: pmq   Source File: InMemoryDbDatasourceConfiguration.java    License: 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 26
Source Project: pmq   Source File: MqConfig.java    License: 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 27
Source Project: charging_pile_cloud   Source File: RedisConfig.java    License: 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 28
Source Project: open-cloud   Source File: JacksonAutoConfiguration.java    License: 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;
}
 
Example 29
Source Project: syhthems-platform   Source File: AuthorizationServerConfig.java    License: 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 30
@Test
public void primaryMetadataIsPropagated() {
	@Configuration class Config {
		@Primary @Bean
		Object foo() { return null; }
	}

	assertTrue("primary metadata was not propagated",
			beanDef(Config.class).isPrimary());
}
 
Example 31
Source Project: yue-library   Source File: AuthServiceAutoConfig.java    License: 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 32
Source Project: tools   Source File: GroupDocConfiguration.java    License: 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 33
Source Project: yue-library   Source File: RedisAutoConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
@Primary
@ConditionalOnBean({ RedisTemplate.class, StringRedisTemplate.class })
public Redis redis(@Qualifier("yueRedisTemplate") RedisTemplate<String, Object> redisTemplate, StringRedisTemplate stringRedisTemplate) {
	log.info("【初始化配置-Redis客户端】配置项:{},默认使用 {} 进行Redis存储对象序列/反序列化。Bean:Redis ... 已初始化完毕。", 
			RedisProperties.PREFIX,
			ClassUtils.getClassName(RedisSerializerEnum.class, false).concat(".JDK"));
	return new Redis(redisTemplate, stringRedisTemplate);
}
 
Example 34
Source Project: java-technology-stack   Source File: PrimaryDataSourceTests.java    License: MIT License 5 votes vote down vote up
@Primary
@Bean
public DataSource primaryDataSource() {
	// @formatter:off
	return new EmbeddedDatabaseBuilder()
			.generateUniqueName(true)
			.addScript("classpath:/org/springframework/test/context/jdbc/schema.sql")
			.build();
	// @formatter:on
}
 
Example 35
Source Project: runscore   Source File: XssConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
@Primary
public ObjectMapper xssObjectMapper(Jackson2ObjectMapperBuilder builder) {
	ObjectMapper objectMapper = builder.createXmlMapper(false).build();
	SimpleModule xssModule = new SimpleModule();
	xssModule.addSerializer(new XssStringJsonSerializer());
	objectMapper.registerModule(xssModule);
	return objectMapper;
}
 
Example 36
Source Project: RuoYi-Vue   Source File: DruidConfig.java    License: MIT License 5 votes vote down vote up
@Bean(name = "dynamicDataSource")
@Primary
public DynamicDataSource dataSource(DataSource masterDataSource)
{
    Map<Object, Object> targetDataSources = new HashMap<>();
    targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource);
    setDataSource(targetDataSources, DataSourceType.SLAVE.name(), "slaveDataSource");
    return new DynamicDataSource(masterDataSource, targetDataSources);
}
 
Example 37
Source Project: txle   Source File: PrimaryConfig.java    License: 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 38
Source Project: DataSphereStudio   Source File: DSSMybatisConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean(name = "dataSource", destroyMethod = "close")
@Primary
public DataSource dataSource() {
    BasicDataSource datasource = new BasicDataSource();
    String dbUrl = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_URL.getValue();
    String username = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_USERNAME.getValue();
    String password = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_PASSWORD.getValue();
    String driverClassName = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_DRIVER_CLASS_NAME.getValue();
    int initialSize = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_INITIALSIZE.getValue();
    int minIdle = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_MINIDLE.getValue();
    int maxActive = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_MAXACTIVE.getValue();
    int maxWait = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_MAXWAIT.getValue();
    int timeBetweenEvictionRunsMillis = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_TBERM.getValue();
    int minEvictableIdleTimeMillis = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_MEITM.getValue();
    String validationQuery = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_VALIDATIONQUERY.getValue();
    boolean testWhileIdle = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_TESTWHILEIDLE.getValue();
    boolean testOnBorrow = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_TESTONBORROW.getValue();
    boolean testOnReturn = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_TESTONRETURN.getValue();
    boolean poolPreparedStatements = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_POOLPREPAREDSTATEMENTS.getValue();
    datasource.setUrl(dbUrl);
    datasource.setUsername(username);
    datasource.setPassword(password);
    datasource.setDriverClassName(driverClassName);
    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);
    logger.info("Database connection address information(数据库连接地址信息)=" + dbUrl);
    return datasource;
}
 
Example 39
Source Project: spring-boot-samples   Source File: SeataConfiguration.java    License: Apache License 2.0 4 votes vote down vote up
@Primary
@Bean("dataSource")
public DataSourceProxy dataSource(DataSource hikariDataSource) {
    return new DataSourceProxy(hikariDataSource);
}
 
Example 40
Source Project: seata-samples   Source File: DataSourceConfiguration.java    License: Apache License 2.0 4 votes vote down vote up
@Primary
@Bean("dataSource")
public DataSourceProxy dataSource(DataSource druidDataSource){
    return new DataSourceProxy(druidDataSource);
}