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

The following examples show how to use org.springframework.context.annotation.Bean. 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 check out the related API usage on the sidebar.
Example 1
@Bean
public HandlerMapping webSocketMessagingHandlerMapping(MessagingManager messagingManager,
                                       UserTokenManager userTokenManager,
                                       ReactiveAuthenticationManager authenticationManager) {


    WebSocketMessagingHandler messagingHandler=new WebSocketMessagingHandler(
        messagingManager,
        userTokenManager,
        authenticationManager
    );
    final Map<String, WebSocketHandler> map = new HashMap<>(1);
    map.put("/messaging/**", messagingHandler);

    final SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
    mapping.setOrder(Ordered.HIGHEST_PRECEDENCE);
    mapping.setUrlMap(map);
    return mapping;
}
 
Example 2
Source Project: cloud-service   Source File: AuthorizationServerConfig.java    License: MIT License 6 votes vote down vote up
/**
 * Jwt资源令牌转换器<br>
 * 参数access_token.store-jwt为true时用到
 *
 * @return accessTokenConverter
 */
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
    JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter() {
        @Override
        public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
            OAuth2AccessToken oAuth2AccessToken = super.enhance(accessToken, authentication);
            addLoginUserInfo(oAuth2AccessToken, authentication); // 2019.07.13 将当前用户信息追加到登陆后返回数据里
            return oAuth2AccessToken;
        }
    };
    DefaultAccessTokenConverter defaultAccessTokenConverter = (DefaultAccessTokenConverter) jwtAccessTokenConverter
            .getAccessTokenConverter();
    DefaultUserAuthenticationConverter userAuthenticationConverter = new DefaultUserAuthenticationConverter();
    userAuthenticationConverter.setUserDetailsService(userDetailsService);

    defaultAccessTokenConverter.setUserTokenConverter(userAuthenticationConverter);
    // 2019.06.29 这里务必设置一个,否则多台认证中心的话,一旦使用jwt方式,access_token将解析错误
    jwtAccessTokenConverter.setSigningKey(signingKey);

    return jwtAccessTokenConverter;
}
 
Example 3
Source Project: springboot-learn   Source File: SwaggerConfig.java    License: MIT License 6 votes vote down vote up
@Bean
public Docket createRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            // api基础信息
            .apiInfo(apiInfo())
            // 控制开启或关闭swagger
            .enable(swaggerEnabled)
            // 选择那些路径和api会生成document
            .select()
            // 扫描展示api的路径包
            .apis(RequestHandlerSelectors.basePackage("com.example.springbootswagger.controller"))
            // 对所有路径进行监控
            .paths(PathSelectors.any())
            // 构建
            .build();
}
 
Example 4
Source Project: springboot-learn   Source File: ShiroConfig.java    License: MIT License 6 votes vote down vote up
/**
 * 会话管理器
 */
@Bean
public DefaultWebSessionManager sessionManager() {
    DefaultWebSessionManager manager = new DefaultWebSessionManager();
    // 加入缓存管理器
    manager.setCacheManager(getEhCacheManager());
    // 删除过期的session
    manager.setDeleteInvalidSessions(true);
    // 设置全局session超时时间
    manager.setGlobalSessionTimeout(30 * 60 * 1000);
    // 是否定时检查session
    manager.setSessionValidationSchedulerEnabled(true);
    // 自定义SessionDao
    manager.setSessionDAO(new EnterpriseCacheSessionDAO());
    return manager;
}
 
Example 5
Source Project: java-master   Source File: DatabaseConfig.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 使用内嵌数据库
 */
@Bean
public DataSource h2DataSource() {
    return new EmbeddedDatabaseBuilder()
            .setType(EmbeddedDatabaseType.H2)
            .addScript("sql-script/schema.sql")
            .addScript("sql-script/data.sql")
            .build();
}
 
Example 6
Source Project: mall-swarm   Source File: RabbitMqConfig.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 将订单队列绑定到交换机
 */
@Bean
Binding orderBinding(DirectExchange orderDirect,Queue orderQueue){
    return BindingBuilder
            .bind(orderQueue)
            .to(orderDirect)
            .with(QueueEnum.QUEUE_ORDER_CANCEL.getRouteKey());
}
 
Example 7
Source Project: yaks   Source File: PetstoreConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public EndpointAdapter handlePutRequestAdapter() {
    return new StaticEndpointAdapter() {
        @Override
        protected Message handleMessageInternal(Message request) {
            return new HttpMessage()
                    .contentType(MediaType.APPLICATION_JSON_VALUE)
                    .status(HttpStatus.OK);
        }
    };
}
 
Example 8
@Bean
public Customizer<ReactiveHystrixCircuitBreakerFactory> defaultConfig() {
	return factory -> factory.configureDefault(id -> {
		return HystrixObservableCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(id))
				.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
						.withExecutionTimeoutInMilliseconds(3000));

	});
}
 
Example 9
Source Project: txle   Source File: AlphaConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public ServerStartable serverStartable(TxConsistentService txConsistentService, GrpcServerConfig serverConfig,
                                       Map<String, Map<String, OmegaCallback>> omegaCallbacks,
                                       Tracing tracing, IAccidentHandlingService accidentHandlingService,
                                       GlobalTxHandler globalTxHandler, CompensateService compensateService, ITxleEhCache txleEhCache, TxleMysqlCache mysqlCache,
                                       TxEventRepository eventRepository, IBusinessDBLatestDetailService businessDBLatestDetailService) {
  ServerStartable starTable = buildGrpc(serverConfig, txConsistentService, omegaCallbacks, tracing, accidentHandlingService, globalTxHandler,
          compensateService, txleEhCache, mysqlCache, eventRepository, businessDBLatestDetailService);
  new Thread(starTable::start).start();
  return starTable;
}
 
Example 10
@Bean
public ThreadPoolTaskExecutor clientOutboundChannelExecutor() {
	TaskExecutorRegistration reg = getClientOutboundChannelRegistration().taskExecutor();
	ThreadPoolTaskExecutor executor = reg.getTaskExecutor();
	executor.setThreadNamePrefix("clientOutboundChannel-");
	return executor;
}
 
Example 11
Source Project: hedera-mirror-node   Source File: CacheConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean(EXPIRE_AFTER_5M)
@Primary
CacheManager cacheManager5m() {
    CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager();
    caffeineCacheManager.setCacheSpecification("maximumSize=100,expireAfterWrite=5m");
    return caffeineCacheManager;
}
 
Example 12
@Bean
@ConditionalOnMissingBean(name = "rabbitListenerContainerFactory")
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(
    SimpleRabbitListenerContainerFactoryConfigurer configurer, ConnectionFactory connectionFactory) {
    SimpleRabbitListenerContainerFactoryExtend factory = new SimpleRabbitListenerContainerFactoryExtend();
    configurer.configure(factory, connectionFactory);
    return factory;
}
 
Example 13
Source Project: mogu_blog_v2   Source File: DruidConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public ServletRegistrationBean statViewServlet() {
    ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
    Map<String, String> initParams = new HashMap<>();

    initParams.put("loginUsername", "admin");
    initParams.put("loginPassword", "123456");
    initParams.put("allow", "");//默认就是允许所有访问

    bean.setInitParameters(initParams);
    return bean;
}
 
Example 14
Source Project: Demo   Source File: CsvBatchConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public JobRepository jobRepository(DataSource dataSource, PlatformTransactionManager transactionManager)
        throws Exception {
    JobRepositoryFactoryBean jobRepositoryFactoryBean = new JobRepositoryFactoryBean();
    jobRepositoryFactoryBean.setDataSource(dataSource);
    jobRepositoryFactoryBean.setTransactionManager(transactionManager);
    jobRepositoryFactoryBean.setDatabaseType("mysql");
    return jobRepositoryFactoryBean.getObject();
}
 
Example 15
/**
 * Hateoas hal provider hateoas hal provider.
 *
 * @return the hateoas hal provider
 */
@Bean
@ConditionalOnMissingBean
@Lazy(false)
HateoasHalProvider hateoasHalProvider() {
	return new HateoasHalProvider();
}
 
Example 16
@Bean
@ConditionalOnBean(SecureRuleRegistry.class)
public List<Rule> ruleListFromRegistry(SecureRuleRegistry secureRuleRegistry) {
	List<Rule> ruleList = secureRuleRegistry.getRuleList();
	if (CollectionUtils.isEmpty(ruleList)) {
		throw new IllegalArgumentException("规则列表不能为空");
	}
	return ruleList;
}
 
Example 17
Source Project: mall-learning   Source File: Swagger2Config.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public Docket createRestApi(){
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .select()
            //为当前包下controller生成API文档
            .apis(RequestHandlerSelectors.basePackage("com.macro.mall.tiny.controller"))
            .paths(PathSelectors.any())
            .build()
            //添加登录认证
            .securitySchemes(securitySchemes())
            .securityContexts(securityContexts());
}
 
Example 18
Source Project: data-highway   Source File: TruckParkConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
Map<TopicPartition, Offsets> endOffsets(
    @Value("${road.topic}") String topic,
    @Value("${road.offsets}") String offsets) {
  return Splitter.on(';').withKeyValueSeparator(':').split(offsets).entrySet().stream().map(e -> {
    int partition = parseInt(e.getKey());
    List<Long> o = Splitter.on(',').splitToList(e.getValue()).stream().map(Long::parseLong).collect(toList());
    return new Offsets(partition, o.get(0), o.get(1));
  }).collect(toMap(o -> new TopicPartition(topic, o.getPartition()), identity()));
}
 
Example 19
Source Project: ZTuoExchange_framework   Source File: ShiroConfig.java    License: MIT License 5 votes vote down vote up
/**
 * 设置rememberMe  Cookie 7天
 * @return
 */
@Bean(name="simpleCookie")
public SimpleCookie getSimpleCookie(){
    SimpleCookie simpleCookie = new SimpleCookie();
    simpleCookie.setName("rememberMe");
    simpleCookie.setHttpOnly(true);
    simpleCookie.setMaxAge(7*24*60*60);
    return simpleCookie ;
}
 
Example 20
@Bean
public DataSource dataSource() {
	return new EmbeddedDatabaseBuilder()//
	.addScript("classpath:/org/springframework/test/jdbc/schema.sql")//
	// Ensure that this in-memory database is only used by this class:
	.setName(getClass().getName())//
	.build();
}
 
Example 21
@Bean
@SuppressWarnings("deprecation")
public SimpUserRegistry userRegistry() {
	SimpUserRegistry registry = createLocalUserRegistry();
	if (registry == null) {
		registry = createLocalUserRegistry(getBrokerRegistry().getUserRegistryOrder());
	}
	boolean broadcast = getBrokerRegistry().getUserRegistryBroadcast() != null;
	return (broadcast ? new MultiServerUserRegistry(registry) : registry);
}
 
Example 22
Source Project: hedera-mirror-node   Source File: GrpcConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
CompositeHealthContributor grpcServices(GrpcServiceDiscoverer grpcServiceDiscoverer,
                                        HealthStatusManager healthStatusManager) {

    Map<String, HealthIndicator> healthIndicators = new LinkedHashMap<>();

    for (GrpcServiceDefinition grpcService : grpcServiceDiscoverer.findGrpcServices()) {
        String serviceName = grpcService.getDefinition().getServiceDescriptor().getName();
        healthIndicators.put(serviceName, new GrpcHealthIndicator(healthStatusManager, serviceName));
    }

    return CompositeHealthContributor.fromMap(healthIndicators);
}
 
Example 23
Source Project: springcloud-oauth2   Source File: RedisConfig.java    License: MIT License 5 votes vote down vote up
/**
 * 字符串模板
 *
 * @param redisConnectionFactory
 * @return
 */
@Bean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
    StringRedisTemplate template = new StringRedisTemplate();
    template.setConnectionFactory(redisConnectionFactory);
    template.setKeySerializer(new StringRedisSerializer());
    return template;
}
 
Example 24
Source Project: code   Source File: MyRedisConfig.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *  RedisCache 自定义序列化规则
 */
@Bean
public RedisCacheConfiguration redisCacheConfiguration() {
    RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig();
    configuration = configuration.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer())).entryTtl(Duration.ofDays(30));
    return configuration;
}
 
Example 25
Source Project: datax-web   Source File: SecurityConfig.java    License: MIT License 5 votes vote down vote up
@Bean
CorsConfigurationSource corsConfigurationSource() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.addAllowedMethod(Constants.SPLIT_STAR);
    config.applyPermitDefaultValues();
    source.registerCorsConfiguration("/**", config);
    return source;
}
 
Example 26
@Bean
public CacheResolver namedCacheResolver() {
	NamedCacheResolver resolver = new NamedCacheResolver();
	resolver.setCacheManager(cacheManager());
	resolver.setCacheNames(Collections.singleton("secondary"));
	return resolver;
}
 
Example 27
Source Project: spring-boot-security-rest   Source File: WebSecurityConfig.java    License: MIT License 4 votes vote down vote up
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
	return super.authenticationManagerBean();
}
 
Example 28
Source Project: txle   Source File: PrimaryConfig.java    License: Apache License 2.0 4 votes vote down vote up
@Primary
@Bean(name = "primaryTransactionManager")
public PlatformTransactionManager transactionManager(@Qualifier("primaryEntityManagerFactory") EntityManagerFactory factory) {
    return new JpaTransactionManager(factory);
}
 
Example 29
Source Project: jeecg-cloud   Source File: RateLimiterConfiguration.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * IP限流 (通过exchange对象可以获取到请求信息,这边用了HostName)
 */
@Bean
@Primary
public KeyResolver ipKeyResolver() {
	return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
}
 
Example 30
Source Project: spring-analysis-note   Source File: WebFluxConfigurationSupport.java    License: MIT License 4 votes vote down vote up
@Bean
public HandlerFunctionAdapter handlerFunctionAdapter() {
	return new HandlerFunctionAdapter();
}