下面列出了怎么用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;
}
/**
* 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;
}
@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();
}
/**
* 会话管理器
*/
@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;
}
/**
* 使用内嵌数据库
*/
@Bean
public DataSource h2DataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("sql-script/schema.sql")
.addScript("sql-script/data.sql")
.build();
}
/**
* 将订单队列绑定到交换机
*/
@Bean
Binding orderBinding(DirectExchange orderDirect,Queue orderQueue){
return BindingBuilder
.bind(orderQueue)
.to(orderDirect)
.with(QueueEnum.QUEUE_ORDER_CANCEL.getRouteKey());
}
@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));
});
}
@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;
}
@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;
}
@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;
}
@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();
}
@Bean
@ConditionalOnBean(SecureRuleRegistry.class)
public List<Rule> ruleListFromRegistry(SecureRuleRegistry secureRuleRegistry) {
List<Rule> ruleList = secureRuleRegistry.getRuleList();
if (CollectionUtils.isEmpty(ruleList)) {
throw new IllegalArgumentException("规则列表不能为空");
}
return ruleList;
}
@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());
}
@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()));
}
/**
* 设置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);
}
@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);
}
/**
* 字符串模板
*
* @param redisConnectionFactory
* @return
*/
@Bean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
template.setKeySerializer(new StringRedisSerializer());
return template;
}
/**
* RedisCache 自定义序列化规则
*/
@Bean
public RedisCacheConfiguration redisCacheConfiguration() {
RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig();
configuration = configuration.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer())).entryTtl(Duration.ofDays(30));
return configuration;
}
@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();
}
@Primary
@Bean(name = "primaryTransactionManager")
public PlatformTransactionManager transactionManager(@Qualifier("primaryEntityManagerFactory") EntityManagerFactory factory) {
return new JpaTransactionManager(factory);
}
/**
* IP限流 (通过exchange对象可以获取到请求信息,这边用了HostName)
*/
@Bean
@Primary
public KeyResolver ipKeyResolver() {
return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
}
@Bean
public HandlerFunctionAdapter handlerFunctionAdapter() {
return new HandlerFunctionAdapter();
}