在Play for Scala中访问Singleton值

时间:2016-07-10 05:46:58

标签: scala playframework playframework-2.0

我在Scala中定义了以下单例

package main

import javax.inject._

@Singleton
class Properties {
  val timeout = 120
}

如何从其他程序访问它?我尝试了main.Properties.timeout但是它抛出了一个编译错误,说没有找到一个伴随对象

1 个答案:

答案 0 :(得分:1)

如果您想以您所提及的方式访问它:from django import forms from django.contrib.auth import authenticate, get_user_model, login, logout from django.contrib.auth.forms import UserCreationForm User = get_user_model class UserLoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) def clean(self, *args, **kwargs): username = self.cleaned_data.get("username") password = self.cleaned_data.get("password") user = authenticate(username=username, password=password) #user_qs = User.objects.filter(username=username) #if user_qs.count() == 1: # user = user_qs.first() if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError("This user does not exist.") if not user.check_password(password): raise forms.ValidationError("Incorrect password.") if not user.is_active: raise forms.ValidationError("User is not active.") return super(UserLoginForm, self).clean(*args, **kwargs) class InceptionForm(forms.ModelForm): email2 = forms.EmailField(label='Confirm Email') class Meta: model = User fields = ('username', 'email', 'password1', 'password2') ,请改为使用随播对象:

main.Properties.timeout

使用class Properties { // ... } object Properties { val timeout = 120 // ... } 注释,您必须在某处注入该服务,才能使用它。所以像这样:

@Singleton

以下是关于PlayFramework的DI的文档:https://www.playframework.com/documentation/2.5.x/ScalaDependencyInjection - 最新的(不是2.0),但它是一个很好的起点。