org.springframework.context.annotation.Bean Java Examples

The following examples show how to use org.springframework.context.annotation.Bean. 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: AuthorizationServerConfig.java    From cloud-service with MIT License 7 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 #2
Source File: WebSocketMessagingHandlerConfiguration.java    From jetlinks-community with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: SwaggerConfig.java    From springboot-learn with 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 File: ShiroConfig.java    From springboot-learn with 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 File: Swagger2Config.java    From mall-learning with 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 #6
Source File: PetstoreConfiguration.java    From yaks with 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 #7
Source File: RabbitMqConfig.java    From mall-swarm with 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 #8
Source File: ReactiveHystrixCircuitbreakerDemoApplication.java    From spring-cloud-circuitbreaker-demo with Apache License 2.0 5 votes vote down vote up
@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 File: CacheResolverCustomizationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Bean
public CacheResolver namedCacheResolver() {
	NamedCacheResolver resolver = new NamedCacheResolver();
	resolver.setCacheManager(cacheManager());
	resolver.setCacheNames(Collections.singleton("secondary"));
	return resolver;
}
 
Example #10
Source File: SecurityConfig.java    From datax-web with 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 #11
Source File: MyRedisConfig.java    From code with 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 #12
Source File: RedisConfig.java    From springcloud-oauth2 with 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 #13
Source File: GrpcConfiguration.java    From hedera-mirror-node with 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 #14
Source File: AbstractMessageBrokerConfiguration.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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 #15
Source File: AlphaConfig.java    From txle with 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 #16
Source File: AbstractMessageBrokerConfiguration.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Bean
public ThreadPoolTaskExecutor clientOutboundChannelExecutor() {
	TaskExecutorRegistration reg = getClientOutboundChannelRegistration().taskExecutor();
	ThreadPoolTaskExecutor executor = reg.getTaskExecutor();
	executor.setThreadNamePrefix("clientOutboundChannel-");
	return executor;
}
 
Example #17
Source File: CacheConfiguration.java    From hedera-mirror-node with 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 #18
Source File: TransactionalAnnotatedConfigClassWithAtConfigurationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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 #19
Source File: RabbitAnnotationDrivenConfiguration.java    From summerframework with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean(name = "rabbitListenerContainerFactory")
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(
    SimpleRabbitListenerContainerFactoryConfigurer configurer, ConnectionFactory connectionFactory) {
    SimpleRabbitListenerContainerFactoryExtend factory = new SimpleRabbitListenerContainerFactoryExtend();
    configurer.configure(factory, connectionFactory);
    return factory;
}
 
Example #20
Source File: DruidConfig.java    From mogu_blog_v2 with 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 #21
Source File: CsvBatchConfig.java    From Demo with 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 #22
Source File: SpringDocHateoasConfiguration.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Hateoas hal provider hateoas hal provider.
 *
 * @return the hateoas hal provider
 */
@Bean
@ConditionalOnMissingBean
@Lazy(false)
HateoasHalProvider hateoasHalProvider() {
	return new HateoasHalProvider();
}
 
Example #23
Source File: SecureConfiguration.java    From magic-starter with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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 #24
Source File: ShiroConfig.java    From ZTuoExchange_framework with 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 #25
Source File: TruckParkConfiguration.java    From data-highway with 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 #26
Source File: DatabaseConfig.java    From java-master with 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 #27
Source File: DemoApp.java    From sbp with Apache License 2.0 4 votes vote down vote up
@Bean
public ApplicationContextAware multiApplicationContextProviderRegister() {
    return ApplicationContextProvider::registerApplicationContext;
}
 
Example #28
Source File: AdminServerAutoConfiguration.java    From Moss with Apache License 2.0 4 votes vote down vote up
@Bean(initMethod = "start", destroyMethod = "stop")
@ConditionalOnMissingBean
public EndpointDetectionTrigger endpointDetectionTrigger(EndpointDetector endpointDetector,
                                                         Publisher<InstanceEvent> events) {
    return new EndpointDetectionTrigger(endpointDetector, events);
}
 
Example #29
Source File: MySqlDatasourceConfiguration.java    From pmq with Apache License 2.0 4 votes vote down vote up
@Bean(name = "mysqlTransactionManager")
@Primary
public DataSourceTransactionManager transactionManager(@Qualifier("mysqlDataSource") DataSource dataSource) {
    return new DataSourceTransactionManager(dataSource);
}
 
Example #30
Source File: KafkaBasicsApplication.java    From spring_io_2019 with Apache License 2.0 4 votes vote down vote up
@Bean
ProducerFactory<Long, Rating> ratingsProducerFactory() {
	return new DefaultKafkaProducerFactory<>(producerConfigs());
}