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

项目:spring-boot-starter-rocketmq    文件:RocketMQAutoConfiguration.java   
@Bean
@ConditionalOnClass(DefaultMQProducer.class)
@ConditionalOnMissingBean(DefaultMQProducer.class)
@ConditionalOnProperty(prefix = "spring.rocketmq", value = {"nameServer", "producer.group"})
public DefaultMQProducer mqProducer(RocketMQProperties rocketMQProperties) {

    RocketMQProperties.Producer producerConfig = rocketMQProperties.getProducer();
    String groupName = producerConfig.getGroup();
    Assert.hasText(groupName, "[spring.rocketmq.producer.group] must not be null");

    DefaultMQProducer producer = new DefaultMQProducer(producerConfig.getGroup());
    producer.setNamesrvAddr(rocketMQProperties.getNameServer());
    producer.setSendMsgTimeout(producerConfig.getSendMsgTimeout());
    producer.setRetryTimesWhenSendFailed(producerConfig.getRetryTimesWhenSendFailed());
    producer.setRetryTimesWhenSendAsyncFailed(producerConfig.getRetryTimesWhenSendAsyncFailed());
    producer.setMaxMessageSize(producerConfig.getMaxMessageSize());
    producer.setCompressMsgBodyOverHowmuch(producerConfig.getCompressMsgBodyOverHowmuch());
    producer.setRetryAnotherBrokerWhenNotStoreOK(producerConfig.isRetryAnotherBrokerWhenNotStoreOk());

    return producer;
}
项目:camunda-task-dispatcher    文件:JmsExternalTaskReceiverConfig.java   
@Bean
@Autowired
public DefaultMessageListenerContainer taskMessageListenerContainer(JmsExternalTaskListener externalTaskListener
        , ConnectionFactory receiverConnectionFactory
        , ActiveMQQueue taskQueue) {
    DefaultMessageListenerContainer listenerContainer = new DefaultMessageListenerContainer();
    listenerContainer.setMessageListener(externalTaskListener);
    listenerContainer.setDestination(taskQueue);
    listenerContainer.setConnectionFactory(receiverConnectionFactory);

    listenerContainer.setAcceptMessagesWhileStopping(false);
    listenerContainer.setSessionTransacted(true);
    listenerContainer.setConcurrentConsumers(concurrentConsumers);
    listenerContainer.setMaxMessagesPerTask(maxMessagesPerTask);
    listenerContainer.setReceiveTimeout(receiveTimeout);
    return listenerContainer;
}
项目:spring-seed    文件:SpringSeedRedis.java   
/**
 * this was used to generate unique key for each method, the key will be like:
 * className + methodName + args.
 */
@Bean
public KeyGenerator keyGenerator() {
    return new KeyGenerator() {
        @Override
        public Object generate(Object target, Method method, Object... params) {
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getName());
            sb.append(":");
            sb.append(method.getName());
            sb.append(":");
            for (Object obj : params) {
                sb.append(String.valueOf(obj));
                sb.append(":");
            }
            return sb.toString();
        }
    };
}
项目:TARA-Server    文件:CasCoreAuthenticationHandlersConfiguration.java   
@ConditionalOnMissingBean(name = "jaasAuthenticationHandlers")
@RefreshScope
@Bean
public List<AuthenticationHandler> jaasAuthenticationHandlers() {
    return casProperties.getAuthn().getJaas()
        .stream()
        .filter(jaas -> StringUtils.isNotBlank(jaas.getRealm()))
        .map(jaas -> {
            final JaasAuthenticationHandler h =
                new JaasAuthenticationHandler(jaas.getName(),
                    servicesManager, jaasPrincipalFactory(), null);

            h.setKerberosKdcSystemProperty(jaas.getKerberosKdcSystemProperty());
            h.setKerberosRealmSystemProperty(jaas.getKerberosRealmSystemProperty());
            h.setRealm(jaas.getRealm());
            h.setPasswordEncoder(Beans.newPasswordEncoder(jaas.getPasswordEncoder()));

            if (jaasPasswordPolicyConfiguration != null) {
                h.setPasswordPolicyConfiguration(jaasPasswordPolicyConfiguration);
            }
            h.setPrincipalNameTransformer(Beans.newPrincipalNameTransformer(
                jaas.getPrincipalTransformation()));
            h.setCredentialSelectionPredicate(Beans.newCredentialSelectionPredicate(
                jaas.getCredentialCriteria()));
            return h;
        })
        .collect(Collectors.toList());
}
项目:OperatieBRP    文件:BevragingGbaVerzoekVerwerkerProvider.java   
/**
 * {@link BevragingVerzoekVerwerker} specifiek voor GBA Ad hoc webservice(Persoons)vraag.
 * @return de GBA Ad hoc webservice (Persoons)vraag verwerker
 */
@Bean
@Named("gbaPersoonsvraagWebserviceVerwerker")
public BevragingVerzoekVerwerker<PersoonsvraagWebserviceVerzoek> persoonsvraagWebserviceVerzoekVerwerker() {
    return new GeneriekeBevragingVerzoekVerwerker<PersoonsvraagWebserviceVerzoek, BevragingResultaat>() {
    };
}
项目:cryptoexchange    文件:DbTestConfiguration.java   
@Bean
public DataSource createDataSource() {
    HikariConfig config = new HikariConfig();
    config.setJdbcUrl(this.url);
    config.setUsername(this.username);
    config.setPassword(this.password);
    config.addDataSourceProperty("poolName", this.poolName);
    config.addDataSourceProperty("connectionTimeout", this.connectionTimeout);
    config.addDataSourceProperty("autoCommit", "false");
    return new HikariDataSource(config);
}
项目:OAuth-2.0-Cookbook    文件:GoogleConfiguration.java   
@Bean
public OAuth2ProtectedResourceDetails resourceDetails() {
    AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails();
    details.setClientId(properties.getClientId());
    details.setClientSecret(properties.getClientSecret());

    // URLs retrieved from https://accounts.google.com/.well-known/openid-configuration
    details.setUserAuthorizationUri("https://accounts.google.com/o/oauth2/v2/auth");
    details.setAccessTokenUri("https://www.googleapis.com/oauth2/v4/token");
    details.setPreEstablishedRedirectUri("http://localhost:8080/google/callback");
    details.setScope(Arrays.asList("openid", "email", "profile"));
    details.setUseCurrentUri(false);
    return details;
}
项目:java-api-best-practices    文件:SecurityConfiguration.java   
@Bean
public FilterRegistrationBean corsFilter() {
  FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
  filterRegistrationBean.setFilter(new CorsFilter());
  // Highest priority to authorise OPTION requests.
  filterRegistrationBean.setOrder(0);
  return filterRegistrationBean;
}
项目:Spring-Security-Third-Edition    文件:SecurityConfig.java   
/**
 * LDAP Server Context
 * @return
 */
@Bean
public DefaultSpringSecurityContextSource contextSource() {
    return new DefaultSpringSecurityContextSource(
            Arrays.asList("ldap://corp.jbcpcalendar.com/"), "dc=corp,dc=jbcpcalendar,dc=com"){{

        setUserDn("CN=Administrator,CN=Users,DC=corp,DC=jbcpcalendar,DC=com");
        setPassword("admin123!");
    }};
}
项目:sponge    文件:SpringConfiguration.java   
/**
 * Camel routes for reading RSS feeds. Routes could be also defined in XML, Groovy or scripting knowledge bases.
 *
 * @return route builder.
 */
@Bean
public RouteBuilder rssInputRoute() {
    return new RouteBuilder() {

        // @formatter:off
        @SuppressWarnings("unchecked")
        @Override
        public void configure() throws Exception {
            EngineOperations operations = camelRssEngine().getOperations();
            Map<String, String> rssSources = operations.getVariable(Map.class, CamelRssConstants.VAR_RSS_SOURCES);

            // Read RSS feeds from all configured sources.
            rssSources.forEach((source, url) ->
                    from("rss:" + url + operations.getVariable(CamelRssConstants.VAR_RSS_ENDPOINT_PARAMETERS, "")).routeId(source)
                        .setHeader(HEADER_SOURCE).constant(source)
                        .to("direct:rss"));

            // Gathers RSS from different sources and sends to Sponge engine as a normalized event.
            from("direct:rss").routeId("rss")
                    .marshal().rss()
                    // Deduplicate by title.
                    .idempotentConsumer(xpath("/rss/channel/item/title/text()"),
                            MemoryIdempotentRepository.memoryIdempotentRepository())
                    // Conversion from RSS XML to Sponge event with attributes.
                    .process((exchange) -> exchange.getIn().setBody(operations.event("news")
                            .set("source", exchange.getIn().getHeader(HEADER_SOURCE))
                            .set("channel", CamelUtils.xpath(exchange, "/rss/channel/title/text()"))
                            .set("title", CamelUtils.xpath(exchange, "/rss/channel/item/title/text()"))
                            .set("link", CamelUtils.xpath(exchange, "/rss/channel/item/link/text()"))
                            .set("description", CamelUtils.xpath(exchange, "/rss/channel/item/description/text()"))
                            .make()))
                    //.filter((exchange) -> false)
                    .to("sponge:camelRssEngine");
        }
        // @formatter:on
    };
}
项目:spring-batch-support    文件:SpringBatchDefaultServiceConfiguration.java   
@Bean
@ConditionalOnMissingBean(JobExplorer.class)
public JobExplorer getJobExplorer() throws Exception {
    BatchConfigurer batchConfigurer = getBatchConfigurer();
    if (batchConfigurer != null) {
        return batchConfigurer.getJobExplorer();
    }
    JobExplorerFactoryBean jobExplorerFactoryBean = new JobExplorerFactoryBean();
    jobExplorerFactoryBean.setDataSource(dataSource);
    return jobExplorerFactoryBean.getObject();
}
项目:app-ms    文件:TestConfig.java   
@Bean
public ClientValidator clientValidator() throws Exception {

    final ClientValidator mock = mock(ClientValidator.class);
    when(mock.isValid(eq(GrantTypes.OPENID), anyString())).thenReturn(true);
    return mock;
}
项目:spring-cloud-gcp    文件:GcpPubSubAutoConfiguration.java   
@Bean
@ConditionalOnMissingBean
public SubscriptionAdminClient subscriptionAdminClient() {
    try {
        return SubscriptionAdminClient.create(
                SubscriptionAdminSettings.newBuilder()
                        .setCredentialsProvider(this.finalCredentialsProvider)
                        .build());
    }
    catch (IOException ioe) {
        throw new PubSubException("An error occurred while creating SubscriptionAdminClient.",
                ioe);
    }
}
项目:springboot-seed    文件:Swagger2Config.java   
@Bean
public Docket createRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.wind.web"))
            .paths(PathSelectors.any())
            .build();
}
项目:myblog    文件:ShiroConfig.java   
/**
 * 再加载securityManager
 * @param manager
 * @return
 */
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(@Qualifier("securityManager") SecurityManager manager) {
    AuthorizationAttributeSourceAdvisor advisor=new AuthorizationAttributeSourceAdvisor();
    advisor.setSecurityManager(manager);
    return advisor;
}
项目:Spring-Security-Third-Edition    文件:WebMvcConfig.java   
/**
 * We mention this in the book, but this helps to ensure that the intercept-url patterns prevent access to our
 * controllers. For example, once security has been applied for administrators try commenting out the modifications
 * to the super class and requesting <a
 * href="http://localhost:800/calendar/events/.html">http://localhost:800/calendar/events/.html</a>. You will
 * observe that security is bypassed since it did not match the pattern we provided. In later chapters, we discuss
 * how to secure the service tier which helps mitigate bypassing of the URL based security too.
 */
// FIXME: FInd out what this is and why it is here.
@Bean
public RequestMappingHandlerMapping requestMappingHandlerMapping() {
    RequestMappingHandlerMapping result = new RequestMappingHandlerMapping();
    result.setUseSuffixPatternMatch(false);
    result.setUseTrailingSlashMatch(false);
    return result;
}
项目:yggdrasil-mock    文件:YggdrasilMockServer.java   
@Bean
public ServerMeta serverMeta(@Value("#{publickeyPem}") String publickeyPem) {
    ServerMeta meta = new ServerMeta();
    meta.setSignaturePublickey(publickeyPem);
    meta.setSkinDomains(skinDomains);
    meta.setMeta(ofEntries(
            entry("serverName", "yggdrasil mock server"),
            entry("implementationName", "yggdrasil-mock-server"),
            entry("implementationVersion", "0.0.1")));
    return meta;
}
项目:buabook-api-interface    文件:BuaBookApiInterfaceConfig.java   
@Bean
public TaskScheduler bbTaskScheduler() {
    ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
    taskScheduler.setThreadNamePrefix("API-Schd-ThrP-");
    taskScheduler.setAwaitTerminationSeconds(1);
    taskScheduler.setRejectedExecutionHandler(new ThreadPoolTaskRejectedHandler());

    return taskScheduler;
}
项目:godeye    文件:ZipkinConfig.java   
@Bean
public SpanCollector spanCollector() {
  HttpSpanCollector.Config config =
      HttpSpanCollector.Config.builder()
          .connectTimeout(properties.getConnectTimeout())
          .readTimeout(properties.getReadTimeout())
          .compressionEnabled(properties.isCompressionEnabled())
          .flushInterval(properties.getFlushInterval())
          .build();
  return HttpSpanCollector.create(
      properties.getUrl(), config, new EmptySpanCollectorMetricsHandler());
}
项目:cas-5.1.0    文件:CasOAuthConfiguration.java   
@ConditionalOnMissingBean(name = "requiresAuthenticationAccessTokenInterceptor")
@Bean
@RefreshScope
public SecurityInterceptor requiresAuthenticationAccessTokenInterceptor() {
    final String clients = Stream.of(Authenticators.CAS_OAUTH_CLIENT_BASIC_AUTHN,
            Authenticators.CAS_OAUTH_CLIENT_DIRECT_FORM,
            Authenticators.CAS_OAUTH_CLIENT_USER_FORM).collect(Collectors.joining(","));
    return new SecurityInterceptor(oauthSecConfig(), clients);
}
项目:openaffect-server    文件:SwaggerDocumentationConfig.java   
@Bean
public Docket customImplementation(){
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
                .apis(RequestHandlerSelectors.basePackage("io.openaffect.api"))
                .build()
            .directModelSubstitute(org.joda.time.LocalDate.class, java.sql.Date.class)
            .directModelSubstitute(org.joda.time.DateTime.class, java.util.Date.class)
            .apiInfo(apiInfo());
}
项目:Spring-Security-Third-Edition    文件:AclConfig.java   
@Bean
public LookupStrategy lookupStrategy(){
    BasicLookupStrategy ls = new BasicLookupStrategy(
                                            dataSource,
                                            aclCache(),
                                            aclAuthorizationStrategy(),
                                            consoleAuditLogger());

    ls.setPermissionFactory(permissionFactory());
    return ls;
}
项目:Spring-Security-Third-Edition    文件:WebMvcConfig.java   
@Bean
public ReloadableResourceBundleMessageSource messageSource() {
    ReloadableResourceBundleMessageSource resource = new ReloadableResourceBundleMessageSource();
    resource.setBasenames("/WEB-INF/locales/messages");
    resource.setDefaultEncoding("UTF-8");
    resource.setFallbackToSystemLocale(Boolean.TRUE);
    return resource;
}
项目:springboot    文件:DruidDataSourceConfig.java   
@Bean(name="dataSource")
//标志这个 Bean 如果在多个同类 Bean 候选时,该 Bean 优先被考虑。「多数据源配置的时候注意,必须要有一个主数据源,用 @Primary 标志该 Bean
@Primary
public DataSource dataSource(){
    DruidDataSource druidDataSource = new DruidDataSource();
    druidDataSource.setUrl(url);
    druidDataSource.setUsername(user);
    druidDataSource.setPassword(password);
    druidDataSource.setDriverClassName(driverClass);
    return druidDataSource;

}
项目:Spring-5.0-Cookbook    文件:ReactiveChatSocketConfig.java   
@Bean
public HandlerMapping webSocketMapping() {
    Map<String, WebSocketHandler> map = new HashMap<>();
    map.put("/react", messageWebSocketHandler);

    SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
    mapping.setOrder(10);
    mapping.setUrlMap(map);
    return mapping;
}
项目:Spring-5.0-Cookbook    文件:LoginFuncReactControllers.java   
@Bean
public RouterFunction<ServerResponse> userServiceBox() {
    return route(GET("/listFluxUsers"), loginHandler::userDetailsList)
               .andRoute(GET("/selectUserById/{id}"), loginHandler::userDetailsById)
               .andRoute(POST("/selectFluxUsers"), loginHandler::chooseFluxUserDetails)
               .andRoute(POST("/saveUser"), loginHandler::saveUserdetailsMono)
               .andRoute(GET("/selectUserByFirstName/{fname}"), loginHandler::chooseUserByFirstName)
               .andRoute(GET("/selectUserByLastName/{lname}"), loginHandler::chooseUserByLastName);
}
项目:martini-core    文件:GherkinConfiguration.java   
@Bean
Mixology getMixology(
    @Value("${martini.mixology:#{null}}") Class<? extends Mixology> impl
) {
    return null == impl ?
        beanFactory.createBean(DefaultMixology.class) : beanFactory.createBean(impl);
}
项目:cas-5.1.0    文件:CasCoreWebflowConfiguration.java   
@ConditionalOnMissingBean(name = "requestParameterAuthenticationPolicyWebflowEventResolver")
@Bean
@RefreshScope
public CasWebflowEventResolver requestParameterAuthenticationPolicyWebflowEventResolver() {
    return new RequestParameterMultifactorAuthenticationPolicyEventResolver(authenticationSystemSupport,
            centralAuthenticationService, servicesManager,
            ticketRegistrySupport, warnCookieGenerator,
            authenticationRequestServiceSelectionStrategies, selector, casProperties);
}
项目:cas-5.1.0    文件:ElectronicFenceConfiguration.java   
@ConditionalOnMissingBean(name = "authenticationRiskMitigator")
@Bean
@RefreshScope
public AuthenticationRiskMitigator authenticationRiskMitigator() {
    if (casProperties.getAuthn().getAdaptive().getRisk().getResponse().isBlockAttempt()) {
        return new DefaultAuthenticationRiskMitigator(blockAuthenticationContingencyPlan());
    }
    return new DefaultAuthenticationRiskMitigator(multifactorAuthenticationContingencyPlan());
}
项目:redirector    文件:AbstractFacadeBeans.java   
@Bean
@Scope(AppScope.APP_SCOPE)
public IAppModelFacade modelFacade(String appName, IDataSourceConnector connector, IDataChangePoller dataChangePoller,
                            IWebServiceClient dataFacadeWebServiceClient, ZKConfig config) {
    return new AppModelRestFacade.Builder()
            .withConnector(connector)
            .forApplication(appName)
            .withDataChangePoller(dataChangePoller)
            .withWebServiceClient(dataFacadeWebServiceClient)
            .withZkConfig(config)
            .build();
}
项目:jwala    文件:AemServiceConfiguration.java   
@Bean(name = "webServerService")
public WebServerService getWebServerService(final ResourceService resourceService,
                                            @Qualifier("webServerInMemoryStateManagerService")
                                            final InMemoryStateManagerService<Identifier<WebServer>, WebServerReachableState> inMemoryStateManagerService,
                                            @Value("${paths.resource-templates:../data/templates}") final String templatePath,
                                            @Value("${spring.messaging.topic.serverStates:/topic/server-states}") final String topicServerStates) {
    return new WebServerServiceImpl(
            aemPersistenceServiceConfiguration.getWebServerPersistenceService(),
            resourceService,
            inMemoryStateManagerService,
            templatePath,
            binaryDistributionLockManager);
}
项目:MailTrigger    文件:MailTriggerApplication.java   
@Bean
public Executor asyncExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(2);
    executor.setMaxPoolSize(2);
    executor.setQueueCapacity(500);
    executor.setThreadNamePrefix("MailSender-");
    executor.initialize();

    return executor;
}
项目:Microservices-with-JHipster-and-Spring-Boot    文件:WebConfigurer.java   
@Bean
public CorsFilter corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = jHipsterProperties.getCors();
    if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) {
        log.debug("Registering CORS filter");
        source.registerCorsConfiguration("/api/**", config);
        source.registerCorsConfiguration("/v2/api-docs", config);
    }
    return new CorsFilter(source);
}
项目:talchain    文件:RopstenSample.java   
public static void main(String[] args) throws Exception {
    sLogger.info("Starting EthereumJ!");

    class SampleConfig extends RopstenSampleConfig {
        @Bean
        public RopstenSample sampleBean() {
            return new RopstenSample();
        }
    }

    Ethereum ethereum = EthereumFactory.createEthereum(SampleConfig.class);
}
项目:cas-5.1.0    文件:CasSupportActionsAcceptableUsagePolicyLdapConfiguration.java   
@RefreshScope
@Bean
public AcceptableUsagePolicyRepository acceptableUsagePolicyRepository() {
    final AcceptableUsagePolicyProperties.Ldap ldap = casProperties.getAcceptableUsagePolicy().getLdap();
    final ConnectionFactory connectionFactory = Beans.newLdaptivePooledConnectionFactory(ldap);
    final LdapAcceptableUsagePolicyRepository r = new LdapAcceptableUsagePolicyRepository(ticketRegistrySupport, 
            connectionFactory, ldap.getUserFilter(), ldap.getBaseDn());
    r.setAupAttributeName(casProperties.getAcceptableUsagePolicy().getAupAttributeName());
    return r;
}
项目:EvoMaster    文件:DbDirectIntApplication.java   
@Bean
public Docket piApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .select()
            .paths(regex("/api/db/directint.*"))
            .build();
}
项目:spring-boot-vaadin-rabbitmq-pipeline-demo    文件:AppConfig.java   
@Bean
DataGrid dataGrid() {
    return new DataGrid();
}
项目:grpc-java-contrib    文件:TimeServer.java   
@Bean(initMethod = "start")
public GrpcServerHost grpcServerHost(@Value("${port}") int port) {
    logger.info("Listening for gRPC on port " + port);
    return new GrpcServerHost(port);
}
项目:EasyTransaction    文件:EasyTransTestConfiguration.java   
@Bean
public DataSourceTransactionManager accountingTransactionManager(DataSource accounting){
    return new DataSourceTransactionManager(accounting);
}
项目:xxpay-master    文件:MqConfig.java   
@Bean
public Queue payNotifyQueue() {
    return new ActiveMQQueue(PAY_NOTIFY_QUEUE_NAME);
}