类javax.annotation.PostConstruct源码实例Demo

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

@PostConstruct
public void init() {
    freshPushVersionCache();

    ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
    scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
        @Override
        public void run() {
            Thread.currentThread().setName("fresh-push-version-thread");
            try {
                freshPushVersionCache();
            } catch (Throwable e) {
                logger.error("fresh push version error", e);
            }
        }
    }, 3, 3, TimeUnit.MINUTES);
}
 
源代码2 项目: pmq   文件: MqRestStatController.java
@PostConstruct
public void report() {
	// MetricSingleton.getMetricRegistry().register(MetricRegistry.name("app.Count"),
	// new Gauge<Long>() {
	// @Override
	// public Long getValue() {
	// return appService.getCount();
	// }
	// });
	// MetricSingleton.getMetricRegistry().register(MetricRegistry.name("app.ClusterCount"),
	// new Gauge<Long>() {
	// @Override
	// public Long getValue() {
	// return appClusterService.getClusterCount();
	// }
	// });
	// MetricSingleton.getMetricRegistry().register(MetricRegistry.name("app.InstanceCount"),
	// new Gauge<Long>() {
	// @Override
	// public Long getValue() {
	// return instanceService.getCount();
	// }
	// });
}
 
@PostConstruct
private void initModel() {
    if (!isConfigured()) {
        return;
    }

    magentoGraphqlClient = MagentoGraphqlClient.create(resource);
    productPage = SiteNavigation.getProductPage(currentPage);
    if (productPage == null) {
        productPage = currentPage;
    }

    locale = productPage.getLanguage(false);

    if (magentoGraphqlClient == null) {
        LOGGER.error("Cannot get a GraphqlClient using the resource at {}", resource.getPath());
    } else {
        configureProductsRetriever();
    }
}
 
源代码4 项目: pmq   文件: MqCacheRebuildService.java
@PostConstruct
private void init() {
	cacheCount = soaConfig.getCacheRebuild();
	soaConfig.registerChanged(new Runnable() {
		@Override
		public void run() {
			if (cacheCount != soaConfig.getCacheRebuild()) {
				cacheCount = soaConfig.getCacheRebuild();
				 Map<String, CacheUpdateService> cacheUpdateServices = SpringUtil.getBeans(CacheUpdateService.class);
		            if (cacheUpdateServices != null) {
		                cacheUpdateServices.values().forEach(t1 -> {
		                    t1.forceUpdateCache();
		                });
		            }
			}

		}
	});

}
 
@PostConstruct
protected void initModel() {
    searchTerm = request.getParameter(SearchOptionsImpl.SEARCH_QUERY_PARAMETER_ID);

    // make sure the current page from the query string is reasonable i.e. numeric and over 0
    Integer currentPageIndex = calculateCurrentPageCursor(request.getParameter(SearchOptionsImpl.CURRENT_PAGE_PARAMETER_ID));

    Map<String, String> searchFilters = createFilterMap(request.getParameterMap());

    LOGGER.debug("Detected search parameter {}", searchTerm);

    searchOptions = new SearchOptionsImpl();
    searchOptions.setCurrentPage(currentPageIndex);
    searchOptions.setPageSize(navPageSize);
    searchOptions.setAttributeFilters(searchFilters);
    searchOptions.setSearchQuery(searchTerm);

    // configure sorting
    searchOptions.addSorterKey("relevance", "Relevance", Sorter.Order.DESC);
    searchOptions.addSorterKey("price", "Price", Sorter.Order.ASC);
    searchOptions.addSorterKey("name", "Product Name", Sorter.Order.ASC);
}
 
源代码6 项目: Qualitis   文件: ConfigPrinter.java
@PostConstruct
public void printConfig() throws UnSupportConfigFileSuffixException {
    LOGGER.info("Start to print config");
    addPropertiesFile();
    ResourceLoader resourceLoader = new DefaultResourceLoader();
    LOGGER.info("Prepared to print config in file: {}", propertiesFiles);

    for (String fileName : propertiesFiles) {
        LOGGER.info("======================== Config in {} ========================", fileName);
        PropertySourceLoader propertySourceLoader = getPropertySourceLoader(fileName);
        Resource resource = resourceLoader.getResource(fileName);
        try {
            List<PropertySource<?>> propertySources = propertySourceLoader.load(fileName, resource);
            for (PropertySource p : propertySources) {
                Map<String, Object> map = (Map<String, Object>) p.getSource();
                for (String key : map.keySet()) {
                    LOGGER.info("Name: [{}]=[{}]", key, map.get(key));
                }
            }
        } catch (IOException e) {
            LOGGER.info("Failed to open file: {}, caused by: {}, it does not matter", fileName, e.getMessage());
        }
        LOGGER.info("=======================================================================================\n");
    }
    LOGGER.info("Succeed to print all configs");
}
 
源代码7 项目: tds   文件: OpendapServlet.java
@PostConstruct
public void init() throws javax.servlet.ServletException {
  // super.init();

  logServerStartup.info(getClass().getName() + " initialization start");

  this.ascLimit = ThreddsConfig.getInt("Opendap.ascLimit", ascLimit); // LOOK how the hell can OpendapServlet call
                                                                      // something in the tds module ??
  this.binLimit = ThreddsConfig.getInt("Opendap.binLimit", binLimit);

  this.odapVersionString = ThreddsConfig.get("Opendap.serverVersion", odapVersionString);
  logServerStartup.info(getClass().getName() + " version= " + odapVersionString + " ascLimit = " + ascLimit
      + " binLimit = " + binLimit);

  if (tdsContext != null) // LOOK not set in mock testing enviro ?
  {
    setRootpath(tdsContext.getServletRootDirectory().getPath());
  }

  logServerStartup.info(getClass().getName() + " initialization done");
}
 
@PostConstruct
public void init() {
    jexlEngine = new JexlBuilder().create();
    // 支持的参数
    // 1. 启动参数
    // 2. 测试配置变量
    // 3. 系统属性
    PropertySource<?> ps = environment.getPropertySources().get("systemProperties");
    Map<Object, Object> source = (Map<Object, Object>) ps.getSource();
    source.forEach((key, value) -> {
        if (!jc.has(keyed((String) key))) {
            jc.set(keyed((String) key), value);
        }
    });

    // 4. 环境变量
    ps = environment.getPropertySources().get("systemEnvironment");
    source = (Map<Object, Object>) ps.getSource();
    source.forEach((key, value) -> {
        if (!jc.has(keyed((String) key))) {
            jc.set(keyed((String) key), value);
        }
    });
}
 
源代码9 项目: qconfig   文件: NoTokenPermissionServiceImpl.java
@PostConstruct
public void init() {
    TypedConfig<String> config = TypedConfig.get("no-token-info", TypedConfig.STRING_PARSER);
    config.current();
    config.addListener(new Configuration.ConfigListener<String>() {
        @Override
        public void onLoad(String conf) {
            noTokenInfo = initNoTokenInfo(conf);
            logger.info("change no token info: {}", noTokenInfo);
        }
    });
}
 
源代码10 项目: FEBS-Cloud   文件: JobServiceImpl.java
/**
 * 项目启动时,初始化定时器
 */
@PostConstruct
public void init() {
    List<Job> scheduleJobList = this.baseMapper.queryList();
    // 如果不存在,则创建
    scheduleJobList.forEach(scheduleJob -> {
        CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, scheduleJob.getJobId());
        if (cronTrigger == null) {
            ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
        } else {
            ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);
        }
    });
}
 
源代码11 项目: SENS   文件: FreeMarkerConfig.java
@PostConstruct
public void setSharedVariable() {
    try {
        //shiro
        configuration.setSharedVariable("shiro", new ShiroTags());
        configuration.setNumberFormat("#");

        //自定义标签
        configuration.setSharedVariable("commonTag", commonTagDirective);
        configuration.setSharedVariable("options", optionsService.findAllOptions());
    } catch (TemplateModelException e) {
        log.error("自定义标签加载失败:{}", e.getMessage());
    }
}
 
源代码12 项目: fido2   文件: cachePolicies.java
@PostConstruct
public void initialize() {
    Collection<FidoPolicies> fpCol = getFidoPolicies.getAllActive();
    for(FidoPolicies fp: fpCol){
        FidoPoliciesPK fpPK = fp.getFidoPoliciesPK();
        try{
            FidoPolicyObject fidoPolicyObject = FidoPolicyObject.parse(
                    fp.getPolicy(),
                    fp.getVersion(),
                    (long) fpPK.getDid(),
                    (long) fpPK.getSid(),
                    (long) fpPK.getPid(),
                    fp.getStartDate(),
                    fp.getEndDate());

            MDSClient mds = null;
            if(fidoPolicyObject.getMdsOptions() != null){
                mds = new MDS(fidoPolicyObject.getMdsOptions().getEndpoints());
            }

            String mapkey = fpPK.getSid() + "-" + fpPK.getDid() + "-" + fpPK.getPid();
            skceMaps.getMapObj().put(skfsConstants.MAP_FIDO_POLICIES, mapkey, new FidoPolicyMDSObject(fidoPolicyObject, mds));
        }
        catch(SKFEException ex){
            skfsLogger.log(skfsConstants.SKFE_LOGGER, Level.SEVERE, "SKCE-ERR-1000", "Unable to cache policy: " + ex);
        }
    }

}
 
源代码13 项目: presto   文件: FileStorageService.java
@Override
@PostConstruct
public void start()
{
    deleteStagingFilesAsync();
    createParents(new File(baseStagingDir, "."));
    createParents(new File(baseStorageDir, "."));
    createParents(new File(baseQuarantineDir, "."));
}
 
源代码14 项目: WeEvent   文件: TcpBroker.java
@PostConstruct
public void start() throws Exception {
    if (this.tcpChannel != null) {
        return;
    }

    // tcp
    if (this.weEventConfig.getMqttTcpPort() > 0) {
        log.info("setup MQTT over tcp on port: {}", this.weEventConfig.getMqttTcpPort());

        this.bossGroup = new NioEventLoopGroup();
        this.workerGroup = new NioEventLoopGroup();
        this.tcpChannel = tcpServer(this.weEventConfig.getMqttTcpPort());
    }
}
 
@PostConstruct
public void init() {
    quotes = new HashMap<>();
    for (Company company: Company.values())
    quotes.put(company.name(), new Double(random.nextInt(100) + 50));

}
 
源代码16 项目: pmq   文件: QueueExpansionAlarmService.java
@PostConstruct
private void init() {
	super.init(Constants.QUEUE_EXPANSION, soaConfig.getQueueExpansionCheckInterval(), soaConfig);
	soaConfig.registerChanged(new Runnable() {
		private volatile int interval = soaConfig.getQueueExpansionCheckInterval();
		@Override
		public void run() {
			if (soaConfig.getQueueExpansionCheckInterval() != interval) {
				interval = soaConfig.getQueueExpansionCheckInterval();
				updateInterval(interval);
			}
		}
	});
}
 
@Override
@PostConstruct
protected void init2() {
	if (this.testBean3 == null || this.testBean4 == null) {
		throw new IllegalStateException("Resources not injected");
	}
	super.init2();
}
 
源代码18 项目: txle   文件: IntegrateTxleController.java
@PostConstruct
void init() {
    ManagedChannel channel = ManagedChannelBuilder.forTarget(txleGrpcServerAddress).usePlaintext()/*.maxInboundMessageSize(10 * 1024 * 1024)*/.build();
    this.stubService = TxleTransactionServiceGrpc.newStub(channel);
    this.stubBlockingService = TxleTransactionServiceGrpc.newBlockingStub(channel);
    this.serverStreamObserver = new TxleGrpcServerStreamObserver(this);
    // 正式环境请设置正确的服务名称、IP和类别
    TxleClientConfig clientConfig = TxleClientConfig.newBuilder().setServiceName("actiontech-dble").setServiceIP("0.0.0.0").setServiceCategory("").build();
    stubService.onInitialize(clientConfig, new TxleServerConfigStreamObserver(this));

    this.onInitialize();
    this.initDBSchema();
    new Thread(() -> this.onSynDatabaseFullDose()).start();
}
 
源代码19 项目: bistoury   文件: ReleaseInfoServiceImpl.java
@PostConstruct
public void init() {
    DynamicConfig<LocalDynamicConfig> dynamicConfig = DynamicConfigLoader.load("releaseInfo_config.properties", false);
    dynamicConfig.addListener(aDynamicConfig -> {
        defaultReleaseInfoPath = aDynamicConfig.getString(DEFAULT, DEFAULT_RELEASE_INFO_PATH);
    });
}
 
源代码20 项目: tds   文件: AdminTriggerController.java
@PostConstruct
public void afterPropertiesSet() {

  DebugCommands.Category debugHandler = debugCommands.findCategory("Catalogs");
  DebugCommands.Action act;

  act = new DebugCommands.Action("reportStats", "Make Catalog Report") {
    public void doAction(DebugCommands.Event e) {
      // look want background thread ?
      e.pw.printf("%n%s%n", makeReport());
    }
  };
  debugHandler.addAction(act);

  act = new DebugCommands.Action("reinit", "Read all catalogs") {
    public void doAction(DebugCommands.Event e) {
      // look want background thread ?
      boolean ok = catInit.reread(ConfigCatalogInitialization.ReadMode.always, false);
      e.pw.printf("<p/>Reading all catalogs%n");
      if (ok)
        e.pw.printf("reinit ok%n");
      else
        e.pw.printf("reinit failed%n");
    }
  };
  debugHandler.addAction(act);

  act = new DebugCommands.Action("recheck", "Read changed catalogs") {
    public void doAction(DebugCommands.Event e) {
      // look want background thread ?
      boolean ok = catInit.reread(ConfigCatalogInitialization.ReadMode.check, false);
      e.pw.printf("<p/>Reading changed catalogs%n");
      if (ok)
        e.pw.printf("reinit ok%n");
    }
  };
  debugHandler.addAction(act);
}
 
源代码21 项目: jstarcraft-example   文件: MovieService.java
@PostConstruct
void postConstruct() {
    userDimension = dataModule.getQualityInner("user");
    itemDimension = dataModule.getQualityInner("item");
    scoreDimension = dataModule.getQuantityInner("score");
    qualityOrder = dataModule.getQualityOrder();
    quantityOrder = dataModule.getQuantityOrder();

    // 启动之后每间隔5分钟执行一次
    executor.scheduleAtFixedRate(this::refreshModel, 5, 5, TimeUnit.MINUTES);
}
 
@PostConstruct
public void init() {
    this.initDefaultParm();
    ScheduledExecutorService scheduleReport = Executors.newScheduledThreadPool(1, new NamedThreadFactory());
    scheduleReport.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            try {
                XxlJobExecutor xxlJobExecutor = applicationContext.getBean(XxlJobExecutor.class);
                String adminAddresses = discoveryAdminAddress();
                if (StringUtils.isEmpty(adminAddresses)) {
                    return;
                }
                if (adminAddresses.equals(xxlJobExecutor.getAdminAddresses())) {
                    LOGGER.info("AdminAddresses has no changes.");
                    return;
                }
                if (xxlJobExecutor.getAdminAddresses() == null) {
                    LOGGER.info("Old adminAddresses is NULL");
                } else {
                    LOGGER.info("Remove old node {}", xxlJobExecutor.getAdminAddresses());
                    XxlJobExecutor.getAdminBizList().clear();
                }

                LOGGER.info("Find all adminAddresses:" + adminAddresses + " from eureka");
                xxlJobExecutor.setAdminAddresses(adminAddresses);
                xxlJobExecutor.reInitAdminBizList();
            } catch (Throwable e) {
                LOGGER.warn(e.getMessage(), e);
            }
        }
    }, 0, 30, TimeUnit.SECONDS);
}
 
源代码23 项目: hot-crawler   文件: ReadhubHotProcessor.java
@Override
@PostConstruct
protected void initialize(){
    RequestMethod requestMethod = RequestMethod.GET;
    setFieldsByProperties(siteProperties, requestMethod, generateHeader(),generateRequestBody());
    injectBeansByContext(context);
    setLog(LoggerFactory.getLogger(getClass()));
}
 
@Override
@PostConstruct
protected void init2() {
	if (this.testBean3 == null || this.testBean4 == null) {
		throw new IllegalStateException("Resources not injected");
	}
	super.init2();
}
 
源代码25 项目: arcusplatform   文件: DirectMessageExecutor.java
@PostConstruct
public void init() {
   pool = new ThreadPoolBuilder()
         .withNameFormat("hub-directmsg-%d")
         .withMetrics("hub.direct.message")
         .withMaxPoolSize(poolSize)
         .withCorePoolSize(poolSize)
         .withPrestartCoreThreads(true)
         .withDaemon(true)
         .withMaxBacklog(poolQueueSize)
         .build();
}
 
源代码26 项目: camel-quarkus   文件: CamelResource.java
@PostConstruct
void postConstruct() throws SQLException {
    try (Connection con = dataSource.getConnection()) {
        try (Statement statement = con.createStatement()) {
            try {
                statement.execute("drop table camels");
            } catch (Exception ignored) {
            }
            statement.execute("create table camels (id int primary key, species varchar(255))");
            statement.execute("insert into camels (id, species) values (1, 'Camelus dromedarius')");
            statement.execute("insert into camels (id, species) values (2, 'Camelus bactrianus')");
            statement.execute("insert into camels (id, species) values (3, 'Camelus ferus')");
        }
    }
}
 
源代码27 项目: Moss   文件: JarDependenciesEndpoint.java
@PostConstruct
public void init() {
    CompletableFuture.runAsync(() -> {
        try {
            cachedObject = Analyzer.getAllPomInfo();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    });
}
 
源代码28 项目: molicode   文件: MyWebAppConfiguration.java
@PostConstruct
 public void initEditableValidation(){
    ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer();
    if(initializer.getConversionService()!=null){
        GenericConversionService conversionService = (GenericConversionService) initializer.getConversionService();
        conversionService.addConverter(new StringToDateConverter());
    }
}
 
源代码29 项目: springbootquartzs   文件: QuartzService.java
@PostConstruct
public void startScheduler() {
    try {
        scheduler.start();
    } catch (SchedulerException e) {
        e.printStackTrace();
    }
}
 
源代码30 项目: spring-boot   文件: StoredProcedure1.java
@PostConstruct
void init() {
    // o_name and O_NAME, same
    jdbcTemplate.setResultsMapCaseInsensitive(true);

    simpleJdbcCall = new SimpleJdbcCall(jdbcTemplate)
            .withProcedureName("get_book_by_id");

}
 
 类所在包
 类方法
 同包方法