将参数注入 class 时,何时应将参数声明为 val?
When should I declare a parameter as val when injecting it into a class?
在 MVC Play 应用程序中创建控制器或服务层之类的东西时(使用 javax.inject.Inject
或 com.google.inject.Inject
),我看到依赖注入是按以下方式编写的:
class Controller @Inject()(thing: Something) { ... }
而且我也看到过这样写的:
class Controller @Inject()(val thing: Something) { ... }
写一个比另一个有什么好处吗?有什么区别?
如果我敢猜测,我会认为一个实例化该参数的一个新实例,而另一个实例只是重复使用传入的任何参数的相同实例,但我不知道哪个是哪个我也不知道这样说对不对。
这与注入无关,与 class 属性有关。
class Controller @Inject()(thing: Something) { ... }
它声明了构造函数参数。您可以在 class 正文中使用 thing
。
class Controller @Inject()(val thing: Something) { ... }
它创建 thing
getter。所以它可以在以后用作:
class Controller @Inject()(val thing: Something) { ... }
val c1 = new Controller('Something')
c1.thing \ here is `Something`
这里有一个很好的主题:Do scala constructor parameters default to private val?
在 MVC Play 应用程序中创建控制器或服务层之类的东西时(使用 javax.inject.Inject
或 com.google.inject.Inject
),我看到依赖注入是按以下方式编写的:
class Controller @Inject()(thing: Something) { ... }
而且我也看到过这样写的:
class Controller @Inject()(val thing: Something) { ... }
写一个比另一个有什么好处吗?有什么区别?
如果我敢猜测,我会认为一个实例化该参数的一个新实例,而另一个实例只是重复使用传入的任何参数的相同实例,但我不知道哪个是哪个我也不知道这样说对不对。
这与注入无关,与 class 属性有关。
class Controller @Inject()(thing: Something) { ... }
它声明了构造函数参数。您可以在 class 正文中使用 thing
。
class Controller @Inject()(val thing: Something) { ... }
它创建 thing
getter。所以它可以在以后用作:
class Controller @Inject()(val thing: Something) { ... }
val c1 = new Controller('Something')
c1.thing \ here is `Something`
这里有一个很好的主题:Do scala constructor parameters default to private val?