类org.springframework.context.annotation.Bean源码实例Demo

下面列出了怎么用org.springframework.context.annotation.Bean的API类实例代码及写法,或者点击链接到github查看源代码。

@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;
}
 
源代码2 项目: cloud-service   文件: AuthorizationServerConfig.java
/**
 * 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;
}
 
源代码3 项目: springboot-learn   文件: SwaggerConfig.java
@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();
}
 
源代码4 项目: springboot-learn   文件: ShiroConfig.java
/**
 * 会话管理器
 */
@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;
}
 
源代码5 项目: java-master   文件: DatabaseConfig.java
/**
 * 使用内嵌数据库
 */
@Bean
public DataSource h2DataSource() {
    return new EmbeddedDatabaseBuilder()
            .setType(EmbeddedDatabaseType.H2)
            .addScript("sql-script/schema.sql")
            .addScript("sql-script/data.sql")
            .build();
}
 
源代码6 项目: mall-swarm   文件: RabbitMqConfig.java
/**
 * 将订单队列绑定到交换机
 */
@Bean
Binding orderBinding(DirectExchange orderDirect,Queue orderQueue){
    return BindingBuilder
            .bind(orderQueue)
            .to(orderDirect)
            .with(QueueEnum.QUEUE_ORDER_CANCEL.getRouteKey());
}
 
源代码7 项目: yaks   文件: PetstoreConfiguration.java
@Bean
public EndpointAdapter handlePutRequestAdapter() {
    return new StaticEndpointAdapter() {
        @Override
        protected Message handleMessageInternal(Message request) {
            return new HttpMessage()
                    .contentType(MediaType.APPLICATION_JSON_VALUE)
                    .status(HttpStatus.OK);
        }
    };
}
 
@Bean
public Customizer<ReactiveHystrixCircuitBreakerFactory> defaultConfig() {
	return factory -> factory.configureDefault(id -> {
		return HystrixObservableCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(id))
				.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
						.withExecutionTimeoutInMilliseconds(3000));

	});
}
 
源代码9 项目: txle   文件: AlphaConfig.java
@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;
}
 
@Bean
public ThreadPoolTaskExecutor clientOutboundChannelExecutor() {
	TaskExecutorRegistration reg = getClientOutboundChannelRegistration().taskExecutor();
	ThreadPoolTaskExecutor executor = reg.getTaskExecutor();
	executor.setThreadNamePrefix("clientOutboundChannel-");
	return executor;
}
 
源代码11 项目: hedera-mirror-node   文件: CacheConfiguration.java
@Bean(EXPIRE_AFTER_5M)
@Primary
CacheManager cacheManager5m() {
    CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager();
    caffeineCacheManager.setCacheSpecification("maximumSize=100,expireAfterWrite=5m");
    return caffeineCacheManager;
}
 
@Bean
@ConditionalOnMissingBean(name = "rabbitListenerContainerFactory")
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(
    SimpleRabbitListenerContainerFactoryConfigurer configurer, ConnectionFactory connectionFactory) {
    SimpleRabbitListenerContainerFactoryExtend factory = new SimpleRabbitListenerContainerFactoryExtend();
    configurer.configure(factory, connectionFactory);
    return factory;
}
 
源代码13 项目: mogu_blog_v2   文件: DruidConfig.java
@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;
}
 
源代码14 项目: Demo   文件: CsvBatchConfig.java
@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();
}
 
/**
 * Hateoas hal provider hateoas hal provider.
 *
 * @return the hateoas hal provider
 */
@Bean
@ConditionalOnMissingBean
@Lazy(false)
HateoasHalProvider hateoasHalProvider() {
	return new HateoasHalProvider();
}
 
源代码16 项目: magic-starter   文件: SecureConfiguration.java
@Bean
@ConditionalOnBean(SecureRuleRegistry.class)
public List<Rule> ruleListFromRegistry(SecureRuleRegistry secureRuleRegistry) {
	List<Rule> ruleList = secureRuleRegistry.getRuleList();
	if (CollectionUtils.isEmpty(ruleList)) {
		throw new IllegalArgumentException("规则列表不能为空");
	}
	return ruleList;
}
 
源代码17 项目: mall-learning   文件: Swagger2Config.java
@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());
}
 
源代码18 项目: data-highway   文件: TruckParkConfiguration.java
@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()));
}
 
源代码19 项目: ZTuoExchange_framework   文件: ShiroConfig.java
/**
 * 设置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 ;
}
 
@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();
}
 
@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);
}
 
源代码22 项目: hedera-mirror-node   文件: GrpcConfiguration.java
@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);
}
 
源代码23 项目: springcloud-oauth2   文件: RedisConfig.java
/**
 * 字符串模板
 *
 * @param redisConnectionFactory
 * @return
 */
@Bean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
    StringRedisTemplate template = new StringRedisTemplate();
    template.setConnectionFactory(redisConnectionFactory);
    template.setKeySerializer(new StringRedisSerializer());
    return template;
}
 
源代码24 项目: code   文件: MyRedisConfig.java
/**
 *  RedisCache 自定义序列化规则
 */
@Bean
public RedisCacheConfiguration redisCacheConfiguration() {
    RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig();
    configuration = configuration.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer())).entryTtl(Duration.ofDays(30));
    return configuration;
}
 
源代码25 项目: datax-web   文件: SecurityConfig.java
@Bean
CorsConfigurationSource corsConfigurationSource() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.addAllowedMethod(Constants.SPLIT_STAR);
    config.applyPermitDefaultValues();
    source.registerCorsConfiguration("/**", config);
    return source;
}
 
@Bean
public CacheResolver namedCacheResolver() {
	NamedCacheResolver resolver = new NamedCacheResolver();
	resolver.setCacheManager(cacheManager());
	resolver.setCacheNames(Collections.singleton("secondary"));
	return resolver;
}
 
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
	return super.authenticationManagerBean();
}
 
源代码28 项目: txle   文件: PrimaryConfig.java
@Primary
@Bean(name = "primaryTransactionManager")
public PlatformTransactionManager transactionManager(@Qualifier("primaryEntityManagerFactory") EntityManagerFactory factory) {
    return new JpaTransactionManager(factory);
}
 
源代码29 项目: jeecg-cloud   文件: RateLimiterConfiguration.java
/**
 * IP限流 (通过exchange对象可以获取到请求信息,这边用了HostName)
 */
@Bean
@Primary
public KeyResolver ipKeyResolver() {
	return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
}
 
@Bean
public HandlerFunctionAdapter handlerFunctionAdapter() {
	return new HandlerFunctionAdapter();
}
 
 同包方法