当前位置: 首页>>代码示例>>Scala>>正文


Scala Service类代码示例

本文整理汇总了Scala中org.springframework.stereotype.Service的典型用法代码示例。如果您正苦于以下问题:Scala Service类的具体用法?Scala Service怎么用?Scala Service使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Service类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。

示例1: ItalianVATIdNumberFinder

//设置package包名称以及导入依赖的类
package org.pdfextractor.algorithm.finder.it

import java.util.Locale

import org.pdfextractor.algorithm.candidate.Candidate
import org.pdfextractor.algorithm.finder.AbstractFinder
import org.pdfextractor.algorithm.finder.it.ItalianRegexPatterns._
import org.pdfextractor.algorithm.parser.{ParseResult, Phrase}
import org.pdfextractor.db.domain.dictionary.PaymentFieldType.VATIN
import org.pdfextractor.db.domain.dictionary.{PaymentFieldType, SupportedLocales}
import org.springframework.stereotype.Service

import scala.collection.mutable
import scala.util.matching.Regex

@Service
class ItalianVATIdNumberFinder
  extends AbstractFinder(SupportedLocales.ITALY, VATIN, ItVatinR, ItVatinValueR, true, true) {

 override def searchValuesFromPhrase(
                                       phrase: Phrase,
                                       parseResult: ParseResult,
                                       valuePattern2: Regex): mutable.Buffer[Candidate] = {
    searchPattern.get
      .findAllIn(parseResult.text)
      .map(getValuePattern.findAllIn(_))
      .filter(isValueAllowed(_))
      .map(buildCandidate1(_))
      .toBuffer
  }

  override def isValueAllowed(value: Any): Boolean = {
    Option(value).isDefined &&
      value.isInstanceOf[String] &&
      value.asInstanceOf[String].length == 11 &&
      value.asInstanceOf[String].matches("""\d*""")
  }

  override def parseValue(raw: String): Any = raw

} 
开发者ID:kveskimae,项目名称:pdfalg,代码行数:42,代码来源:ItalianVATIdNumberFinder.scala

示例2: ItalianNameFinder

//设置package包名称以及导入依赖的类
package org.pdfextractor.algorithm.finder.it

import java.util.Locale

import org.apache.commons.lang3.StringUtils
import org.pdfextractor.algorithm.candidate.{CandidateMetadata, MetaPhraseType}
import org.pdfextractor.algorithm.finder._
import org.pdfextractor.algorithm.finder.it.ItalianRegexPatterns._
import org.pdfextractor.algorithm.parser.{ParseResult, Phrase}
import org.pdfextractor.algorithm.phrase.PhraseTypesRefreshedEvent
import org.pdfextractor.algorithm.regex._
import org.pdfextractor.db.domain.dictionary.PaymentFieldType.NAME
import org.pdfextractor.db.domain.dictionary.SupportedLocales
import org.springframework.stereotype.Service

@Service
class ItalianNameFinder extends AbstractFinder(SupportedLocales.ITALY, NAME, None, None, false) {

  @org.springframework.context.event.EventListener(
    Array(classOf[PhraseTypesRefreshedEvent]))
  def refreshed(): Unit = {
    searchPattern = Some(
      ("^(?ims)" + phraseTypesStore.buildAllPhrases(SupportedLocales.ITALY,
        NAME) + "$").r)
    valuePattern = Some(("^(?ims)(.*)$").r)
  }

  def isValueAllowed(value: Any): Boolean = {
    !isVoidText(value.asInstanceOf[String]) &&
      ItNameForbiddenWordsR.findFirstIn(value.asInstanceOf[String]).isEmpty &&
      ItNameMinR.findFirstIn(value.asInstanceOf[String]).nonEmpty
  }

  def parseValue(raw: String): Any = {
    if (Option(raw).isEmpty) None
    else StringUtils.normalizeSpace(raw).split(",")(0)
  }

  override def buildProperties(phrase: Phrase, parseResult: ParseResult, params: Seq[Any]): Map[CandidateMetadata, Any] = {
    val phraseType = phraseTypesStore.findType(SupportedLocales.ITALY, NAME, phrase.text)
    Map(MetaPhraseType -> phraseType)
  }

} 
开发者ID:kveskimae,项目名称:pdfalg,代码行数:45,代码来源:ItalianNameFinder.scala

示例3: EstonianNameFinder

//设置package包名称以及导入依赖的类
package org.pdfextractor.algorithm.finder.et

import java.util.Locale

import org.apache.commons.lang3.StringUtils
import org.pdfextractor.algorithm.candidate.{Candidate, CandidateMetadata, HasPank, MetaPhraseType}
import org.pdfextractor.algorithm.finder.{AbstractFinder, isPankPresent}
import org.pdfextractor.algorithm.parser.{ParseResult, Phrase}
import org.pdfextractor.algorithm.phrase.PhraseTypesRefreshedEvent
import org.pdfextractor.db.domain.dictionary.PaymentFieldType.NAME
import org.pdfextractor.db.domain.dictionary.SupportedLocales
import org.springframework.stereotype.Service

@Service
class EstonianNameFinder extends AbstractFinder(SupportedLocales.ESTONIA, NAME) {

  @org.springframework.context.event.EventListener(
    Array(classOf[PhraseTypesRefreshedEvent]))
  def refreshed(): Unit = {
    searchPattern = Some(
      ("^(?m)" + phraseTypesStore
        .buildAllStarts(SupportedLocales.ESTONIA, NAME) + "$").r)
    valuePattern = Some(
      ("(?m)" + phraseTypesStore.buildAllPhrases(SupportedLocales.ESTONIA,
        NAME)).r)
  }

  override def isValueAllowed(value: Any) = true

  override def parseValue(raw: String): Any = {
    StringUtils normalizeSpace (raw
      .replaceAll("(Registrikood)(.{0,})", "")
      .split("""[\s]{3,}""")(0))
  }

  override def buildProperties(phrase: Phrase, parseResult: ParseResult, params: Seq[Any]): Map[CandidateMetadata, Any] = {
    val phraseType = phraseTypesStore.findType(SupportedLocales.ESTONIA, NAME, phrase.text)
    val pankPresent = isPankPresent(phrase.text)
    Map(MetaPhraseType -> phraseType, HasPank -> pankPresent)
  }

} 
开发者ID:kveskimae,项目名称:pdfalg,代码行数:43,代码来源:EstonianNameFinder.scala

示例4: EstonianReferenceNumberFinder

//设置package包名称以及导入依赖的类
package org.pdfextractor.algorithm.finder.et

import java.math.BigInteger
import java.util.Locale

import org.pdfextractor.algorithm.finder.et.EstonianRegexPatterns._
import org.pdfextractor.algorithm.finder.{AbstractFinder, _}
import org.pdfextractor.db.domain.dictionary.PaymentFieldType.REFERENCE_NUMBER
import org.pdfextractor.db.domain.dictionary.SupportedLocales
import org.springframework.stereotype.Service

@Service
class EstonianReferenceNumberFinder extends AbstractFinder(SupportedLocales.ESTONIA, REFERENCE_NUMBER, EstRefNoLineR, EstRefNoR) {

  override def parseValue(raw: String): Any = raw

  override def isValueAllowed(raw: Any): Boolean = {
    try {
      val value = new BigInteger(raw.asInstanceOf[String])
      isCorrectFormat(value) && checkDigitMatches(value,
        calculateCheckDigit(value))
    } catch {
      case _: Throwable => false
    }
  }

  private def calculateCheckDigit(value: BigInteger) = {
    val productsSum = calculate731Sum(digitsToPenultimateInReverse(value))

    findTensMultiple(productsSum) - productsSum
  }

  private def checkDigitMatches(value: BigInteger, checkDigit: Int) = {
    val lastDigit =
      Integer.valueOf("" + value.toString.charAt(value.toString.length - 1))
    lastDigit == checkDigit
  }

  private def isCorrectFormat(value: BigInteger): Boolean = {
    Option(value).isDefined &&
      value.signum > 0 && // must be positive
      value.toString.length >= 2 && // must have 2 - 20 digits
      value.toString.length <= 20
  }

} 
开发者ID:kveskimae,项目名称:pdfalg,代码行数:47,代码来源:EstonianReferenceNumberFinder.scala

示例5: EstonianInvoiceIDFinder

//设置package包名称以及导入依赖的类
package org.pdfextractor.algorithm.finder.et

import java.util.Locale

import org.apache.commons.lang3.StringUtils
import org.pdfextractor.algorithm.finder.AbstractFinder
import org.pdfextractor.algorithm.finder.et.EstonianRegexPatterns._
import org.pdfextractor.algorithm.phrase.PhraseTypesRefreshedEvent
import org.pdfextractor.algorithm.regex._
import org.pdfextractor.db.domain.dictionary.PaymentFieldType.INVOICE_ID
import org.pdfextractor.db.domain.dictionary.SupportedLocales
import org.springframework.stereotype.Service

@Service
class EstonianInvoiceIDFinder extends AbstractFinder(SupportedLocales.ESTONIA, INVOICE_ID) {

  @org.springframework.context.event.EventListener(
    Array(classOf[PhraseTypesRefreshedEvent]))
  def refreshed(): Unit = {
    searchPattern = Some(
      ("(?ism)" + phraseTypesStore.buildAllPhrases(SupportedLocales.ESTONIA,
        INVOICE_ID)).r)
    valuePattern = Some(("(?ism)" + phraseTypesStore.buildAllPhrases(
      SupportedLocales.ESTONIA,
      INVOICE_ID) +
      """([.]{0,1})([\s]{0,})([:]{0,1})([\s]{0,})([^\s]{1,})""").r)
  }

  override def isValueAllowed(value: Any): Boolean = {
    EstIBANCorrectR
      .findFirstIn(value.asInstanceOf[String])
      .isEmpty &&
      TwoOrMoreDigitsR
        .findFirstIn(value.asInstanceOf[String])
        .nonEmpty
  }

  override def parseValue(raw: String): Any = StringUtils.normalizeSpace(raw)

} 
开发者ID:kveskimae,项目名称:pdfalg,代码行数:41,代码来源:EstonianInvoiceIDFinder.scala

示例6: RelationBean

//设置package包名称以及导入依赖的类
package pl.writeonly.babel.beans
import javax.annotation.Resource
import org.springframework.stereotype.Service
import pl.writeonly.babel.daos.DaoCrud
import pl.writeonly.babel.entities.Relation
import javax.annotation.Resource
@org.springframework.stereotype.Service
class RelationBean (@Resource(name = "daoImpl") val dao: DaoCrud){
  val clazz = classOf[Relation]
	def persist (relation:Relation) = dao.persist(relation)
	def persistAll(relations :List[Relation]) = dao.persistAll(relations)
	def find() = dao.find(clazz);
	def merge(relation:Relation) = dao.merge(relation);
	def delete(relation:Relation) = dao.delete(relation)
	//def readSort(comparator:Comparator[Relation])
	

} 
开发者ID:writeonly,项目名称:babel,代码行数:19,代码来源:RelationBean.scala

示例7: RecordBean

//设置package包名称以及导入依赖的类
package pl.writeonly.babel.beans
import javax.annotation.Resource
import java.io.BufferedReader
import org.springframework.stereotype.Service
import pl.writeonly.babel.daos.DaoCrud
import pl.writeonly.babel.entities.Record
import pl.writeonly.babel.entities.User
import pl.writeonly.scala.util.ToBoolean
import scala.collection.mutable.MutableList
import pl.writeonly.babel.entities.Relation

@org.springframework.stereotype.Service
class RecordBean(@Resource(name = "daoImpl") val dao: DaoCrud) extends ToBoolean {
  val clazz = classOf[Record]
  def persist(record: Record) = dao.persist(record)
  def persistAll(records: List[Record]) = dao.persistAll(records)
  def find(user: User) = dao.find(clazz);
  def find() = dao.find(clazz)
  def merge(record: Record) = dao.merge(record);

  def parse(reader: BufferedReader): MutableList[Record] = {
    val list = new MutableList[Record]
    do {
      val line: String = reader.readLine
      if (!line) return list
      list += new Record(line)
      var i: Int = new Integer(line).toInt
    } while (true)
    return null
  }
  
  def toRecordAll(relations : List[Relation]) = {
    
  }
} 
开发者ID:writeonly,项目名称:babel,代码行数:36,代码来源:RecordBean.scala

示例8: InfoService

//设置package包名称以及导入依赖的类
package com.github.swwjf.ws

import com.github.swwjf.errorhandling.WSException
import org.springframework.beans.BeanUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.dao.DataIntegrityViolationException
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

import scala.collection.JavaConversions._
import scala.compat.java8.OptionConverters.RichOptionalGeneric

@Service
class InfoService @Autowired()(infoRepository: InfoRepository) {

  def fetchAllInformation(): List[InfoResponseDTO] = {
    def jpaToResponse(jpa: InfoJPA): InfoResponseDTO = {
      val response = InfoResponseDTO(
        createdDate = jpa.createdData.toString,
        updatedDate = Option(jpa.updatedDate).map(_.toString).orNull
      )
      BeanUtils.copyProperties(jpa, response)
      response
    }

    infoRepository
      .findAll()
      .map(jpaToResponse)
      .toList
  }

  def saveInfo(infoRequestDTO: InfoRequestDTO): Unit = {
    def requestToJPA(request: InfoRequestDTO): InfoJPA = {
      val jpa = new InfoJPA
      BeanUtils.copyProperties(request, jpa)
      jpa
    }

    try {
      infoRepository.save(requestToJPA(infoRequestDTO))
    } catch {
      case e: DataIntegrityViolationException => throw new WSException("Invalid/duplicate label")
    }
  }

  @Transactional
  def updateInfo(info: InfoRequestDTO): Unit = {
    val infoJPA = infoRepository
      .findOneByLabel(info.label)
      .asScala
      .getOrElse(throw new WSException(s"Failed to find info by label ${info.label}"))
    infoJPA.setMainDetails(info.mainDetails)
    infoJPA.setComments(info.comments)
  }

} 
开发者ID:andrei-l,项目名称:scala-webapp-with-java-frameworks,代码行数:57,代码来源:InfoService.scala

示例9: VoteService

//设置package包名称以及导入依赖的类
package org.helianto.politikei.service

import org.helianto.politikei.{Proposition, Vote}
import org.helianto.politikei.repository.{PropositionRepository, VoteRepository}
import org.springframework.data.domain.{PageRequest, Sort}
import org.springframework.stereotype.Service

@Service
class VoteService(val repository: VoteRepository, val propositionRepository: PropositionRepository) {

  private[service] def page(page: Int) = new PageRequest(page, 10, Sort.Direction.ASC, "voteDate")

  def all(propositionId: String, p: Int = 0) = repository.findByPropositionId(Option(propositionId).getOrElse(""), page(0))

  def one(voteId: String) = repository.findOne(Option(voteId).getOrElse(""))

  def me(propositionId: String, identityId: String) =
    repository.findByPropositionIdAndIdentityId(Option(propositionId).getOrElse(""), identityId)

  def saveOrUpdate(propositionId: String, identityId: String, value: Int) = {
    require(Option(propositionId).nonEmpty)
    require(Option(identityId).nonEmpty)
    Option(propositionRepository.findOne(propositionId)) match {
      case Some(proposition) =>
        val vote = repository.save {
          Option(repository.findByPropositionIdAndIdentityId(propositionId, identityId))
            .getOrElse(new Vote(propositionId, identityId))
            .merge(value)
        }
        applyTo(proposition)
        vote
      case None => throw new IllegalArgumentException("Proposition must not be null")
    }
  }

  private[service] def applyTo(proposition: Proposition) = {
    import collection.JavaConversions._
    repository.countVote(proposition.id).toList.foreach{i =>
      println(s"VOTE: $i")
      proposition.merge(i)}
    propositionRepository.save(proposition)
  }

} 
开发者ID:iservport,项目名称:iservport-politikei,代码行数:45,代码来源:VoteService.scala

示例10: TasksRepository

//设置package包名称以及导入依赖的类
package com.github.mkorman9.districron.logic

import com.github.mkorman9.districron.{ExecutionStatus, Success}
import com.github.mkorman9.districron.common.ExecutionLock
import com.github.mkorman9.districron.dao.TasksDAO
import com.github.mkorman9.districron.model.Task
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class TasksRepository @Autowired() (tasksDAO: TasksDAO) {
  def readAll: Seq[Task] = {
    tasksDAO.readAll map (new Task(_))
  }

  // locks execution of given task definition to current node
  // returns if lock was created successfully
  def tryToEstablishExecutionLock(task: Task): ExecutionLock = {
    tasksDAO.createTaskExecutionIfThereIsNoOngoingOneInGivenPeriod(
      task.name,
      task.executionInterval
    )
  }

  def markTaskExecutionCompleted(executionId: Long, status: ExecutionStatus): Unit = {
    tasksDAO.updateTaskExecutionStatus(
      executionId,
      status == Success
    )
  }
} 
开发者ID:mkorman9,项目名称:districron,代码行数:32,代码来源:TasksRepository.scala

示例11: MessageSender

//设置package包名称以及导入依赖的类
package com.github.mkorman9.districron.logic

import akka.actor.{ActorRef, ActorSystem}
import akka.cluster.pubsub.DistributedPubSubMediator.{Publish, Send}
import com.github.mkorman9.districron.Messages.ExecuteTask
import com.github.mkorman9.districron.model.Task
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class MessageSender @Autowired() (actorSystem: ActorSystem) {
  def sendMessageToTasksHandlingActor(message: Any): Unit = {
    val tasksHandlingActor = actorSystem.actorSelection(com.github.mkorman9.districron.Actor.Path)
    tasksHandlingActor ! message
  }

  def broadcastExecutionMessage(clusterMediator: ActorRef, sender: ActorRef, executionId: Long, task: Task): Unit = {
    val executeTaskMessage = ExecuteTask(executionId, task.name)

    if (task.globalDistribution)
      clusterMediator.tell(
        Publish(task.recipient, executeTaskMessage),
        sender
      )
    else
      clusterMediator.tell(
        Send(task.recipient, executeTaskMessage, localAffinity = false),
        sender
      )
  }
} 
开发者ID:mkorman9,项目名称:districron,代码行数:32,代码来源:MessageSender.scala

示例12: TasksManager

//设置package包名称以及导入依赖的类
package com.github.mkorman9.districron.logic

import com.github.mkorman9.districron.ExecutionStatus
import com.github.mkorman9.districron.actor.Messages.BroadcastTaskExecutionToRecipients
import com.github.mkorman9.districron.model.Task
import org.slf4j.{Logger, LoggerFactory}
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class TasksManager @Autowired() (tasksRepository: TasksRepository, tasksScheduler: TasksScheduler, messageSender: MessageSender) {
  final val logger: Logger = LoggerFactory.getLogger(classOf[TasksManager])

  def scheduleAllExistingTasks: Unit = {
    tasksScheduler.schedule(tasksRepository.readAll)
  }

  def executeTask(task: Task): Unit = {
    logger.info(s"Trying to get lock for ${task.name}")
    val executionLock = tasksRepository.tryToEstablishExecutionLock(task)

    executionLock match {
      case Some(executionId) => performTaskExecution(executionId, task)
      case None => logger.info(s"Lock for ${task.name} already established by someone else. Skipping execution")
    }
  }

  def completeTaskExecution(executionId: Long, status: ExecutionStatus): Unit = {
    logger.info(s"Task execution $executionId completed with status $status")
    tasksRepository.markTaskExecutionCompleted(executionId, status)
  }

  private def performTaskExecution(executionId: Long, task: Task): Unit = {
    logger.info(s"Lock for ${task.name} established. Proceeding with execution")

    messageSender sendMessageToTasksHandlingActor BroadcastTaskExecutionToRecipients(executionId, task)
  }
} 
开发者ID:mkorman9,项目名称:districron,代码行数:39,代码来源:TasksManager.scala

示例13: TasksScheduler

//设置package包名称以及导入依赖的类
package com.github.mkorman9.districron.logic

import java.util.Date

import com.github.mkorman9.districron.actor.Messages.TaskExecutionTick
import com.github.mkorman9.districron.model.Task
import org.slf4j.{Logger, LoggerFactory}
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.scheduling.support.CronTrigger
import org.springframework.scheduling.{TaskScheduler, Trigger, TriggerContext}
import org.springframework.stereotype.Service

@Service
class TasksScheduler @Autowired() (systemScheduler: TaskScheduler,
                                   messageSender: MessageSender) {
  final val logger: Logger = LoggerFactory.getLogger(classOf[TasksScheduler])

  def schedule(tasks: Seq[Task]): Unit = {
    tasks foreach schedule
  }

  def schedule(task: Task): Unit = {
    logger.info(s"Scheduling task '${task.name}'...")

    systemScheduler.schedule(
      TaskRunnable(task, messageSender),
      CronTriggerConfiguration(task.cronExpression)
    )
  }
}

case class CronTriggerConfiguration(cronExpression: String) extends Trigger {
  final val logger: Logger = LoggerFactory.getLogger(classOf[CronTriggerConfiguration])

  override def nextExecutionTime(triggerContext: TriggerContext): Date = {
    try {
      val trigger = new CronTrigger(cronExpression)
      trigger.nextExecutionTime(triggerContext)
    }
    catch {
      case e: IllegalArgumentException => {
        logger.error(s"Error while scheduling task! Invalid cron expression '$cronExpression'")
        null
      }
    }
  }
}

case class TaskRunnable(task: Task, messageSender: MessageSender) extends Runnable {
  override def run(): Unit = {
    messageSender sendMessageToTasksHandlingActor TaskExecutionTick(task)
  }
} 
开发者ID:mkorman9,项目名称:districron,代码行数:54,代码来源:TasksScheduler.scala

示例14: EchoService

//设置package包名称以及导入依赖的类
package org.helianto.mailer.service

import com.iservport.message.domain.Message
import org.springframework.stereotype.Service

@Service
class EchoService {

  def handle(message: Message) = {
    val received =
      s"""
         |On-line:  [ link ${message.getDefaults.seeOnline} ${message.getDefaults.apiHome}/redirect/${message.getTemplate}/${message.getId} ]
         |
         |id:       ${message.getId}
         |
         |Sent by:  ${message.getSender.contactName} <${message.getSender.contactEmail}>
         |Entity:   ${message.getSender.entityName}
         |Address:  ${message.getSender.address}
         |
         |To:       ${message.getRecipient.contactName} <${message.getRecipient.contactEmail}>
         |Entity:   ${message.getRecipient.entityName}
         |Address:  ${message.getRecipient.address}
         |
         |Subject:  ${message.getMessageData.subject} <${message.getMessageData.title}>
         |
         |${message.getDefaults.greeting}, ${message.getRecipient.contactName}
         |
         |${message.getMessageData.procedure}
         |
         |[ button -> ${message.getMessageData.callToAction} ]
         |
         |${message.getMessageData.fallBack}
         |
         |[ link -> ${message.getDefaults.apiHome}${message.getServicePath}/${message.getId} ]
         |
         |----
         |
         |${message.getDefaults.sentByText} ${message.getSender.contactEmail}
         |${message.getDefaults.disclaimer}
         |${message.getDefaults.ensure}
         |${message.getDefaults.unsubscribeText}, [ link ${message.getDefaults.unsubscribeCaption} -> ${message.getDefaults.apiHome}/${message.getDefaults.unsubscribeService} ]
         |${message.getDefaults.copyright}
         |
       """.stripMargin
    println(received)
    received
  }

} 
开发者ID:iservport,项目名称:helianto-echo-mailer,代码行数:50,代码来源:EchoService.scala

示例15: AtlantaScalaMicroservice

//设置package包名称以及导入依赖的类
package com.ntsdev.http

import akka.actor.ActorSystem
import akka.event.Logging
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives
import akka.stream.ActorMaterializer
import com.ntsdev.config.EnvironmentConfig
import com.ntsdev.http.routes.{HtmlRoutes, JsonRoutes, TwitterRoutes}
import com.ntsdev.service.{PersonService, TwitterService}
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import com.softwaremill.session.{SessionConfig, SessionManager, SessionUtil}
import org.springframework.context.annotation.Primary

import scala.concurrent.{ExecutionContext, Future}

@Service
@Primary
class AtlantaScalaMicroservice extends Directives with EnvironmentConfig {
  implicit val system = ActorSystem()
  implicit val materializer = ActorMaterializer()
  implicit val executor: ExecutionContext = system.dispatcher

  private val sessionConfig = SessionConfig.default(SessionUtil.randomServerSecret())
  implicit val sessionManager = new SessionManager[Map[String, String]](sessionConfig)

  var _personService: PersonService = _

  private val logger = Logging(system, getClass)
  private val htmlRoutes = new HtmlRoutes()
  private val jsonRoutes = new JsonRoutes(_personService)
  private val twitterRoutes = new TwitterRoutes(new TwitterService)

  @Autowired
  def personService_=(service: PersonService){ //TODO: fix spring lifecycle ordering
    _personService = service
    jsonRoutes.personService = service
  }

  def routes = {
    htmlRoutes.route ~ jsonRoutes.route ~ twitterRoutes.route
  }

  logger.info("Starting http server...")

  Http().bindAndHandle(routes, interface, port).flatMap(binding => {
    logger.info(s"Listening on port [$port] interface [$interface]")
    Future.successful(binding)
  })


} 
开发者ID:neilshannon,项目名称:atlanta-scala-microservice,代码行数:54,代码来源:AtlantaScalaMicroservice.scala


注:本文中的org.springframework.stereotype.Service类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。