score:17
Basically, you have two problems:
Property should be mutable, i.e.
var
rather thanval
All methods of Scala
object
arestatic
, whereas Spring expects instance methods. Actually Scala creates a class with instance methods namedUserRest$
behind the scene, and you need to make its singleton instanceUserRest$.MODULE$
available to Spring.
Spring can apply configuration to preexisting singleton instances, but they should be returned by a method, whereasUserRest$.MODULE$
is a field. Thus, you need to create a method to return it.
So, something like this should work:
object UserRest extends RestHelper {
@BeanProperty
var userRepository: UserRepository = null;
def getInstance() = this
...
}
.
<bean id="userRest"
class="com.abc.rest.UserRest"
factory-method = "getInstance">
<property name="userRepository" ref="userRepository"/>
</bean>
You can replace <property>
with @Autowired
, but cannot replace manual bean declaration with @Service
due to problems with singleton instance described above.
See also:
score:0
In addition to https://stackoverflow.com/a/8344485/5479289, it's also possible to add scala package object to Spring context, as well as scala object, using factory method. Compiled package object is usual java class named package, so you can add it to Spring context. After that you will have all Spring's possibilities inside this object, i.e @Autowired, @Value, manual wiring etc.
Test package:
package my.module
package object A {
def getInstance = this
@Autowired
private val b: B = null
}
And spring context xml is:
<beans ...>
...
<bean id="a" class="my.module.A.package" factory-method="getInstance"/>
...
</beans>
score:0
I faced same issue.
I have many services and want to call these @Autowired service from scala objects.
I tried all the above, None of them worked as my expectation.
I have an object named JobConfig.scala
and I want to autowire TableResolver
class and TableResolver
class itself autowire many other classes.
My application is in spring boot and scala.
- Add
src/main/resources/applicationContext.xml
file.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="jobId" class="package.JobConfig"
factory-method="getInstance">
</bean>
</beans>
- Add
XmlBeansConfig.scala
import org.springframework.context.annotation.{Configuration, ImportResource}
@Configuration
@ImportResource(value = Array("classpath*:applicationContext.xml"))
class XmlBeansConfig {
}
- Inside
JobConfig.scala
object JobConfig{
def getInstance = this
@Autowired
var tableResolver: TableResolver = _
}
score:1
What I do is use AutowiredAnnotationBeanPostProcessor to inject the object at construction time.
For example:
object UserRest extends RestHelper {
@Autowired
var userRepository: UserRepository = _
AppConfig.inject(this)
}
@Configuration
class AppConfig extends ApplicationListener[ContextRefreshedEvent] {
// Set the autowiredAnnotationBeanPostProcessor when the Spring context is initialized
def onApplicationEvent(event: ContextRefreshedEvent) {
autowiredAnnotationBeanPostProcessor =
event.applicationContext.
getBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME).
asInstanceOf[AutowiredAnnotationBeanPostProcessor]
}
}
object AppConfig {
var autowiredAnnotationBeanPostProcessor: AutowiredAnnotationBeanPostProcessor = null
def inject(obj: AnyRef) {
autowiredAnnotationBeanPostProcessor.processInjection(obj);
}
}
Now you can use AppConfig.inject() to inject any object whose lifecycle is not controlled by Spring. For example, JPA Entities, etc.
score:1
Normal Autowire from a class that is marked with @Component or @Bean would work with above mentioned ways.
But if you want to auto wire an interface extending Jpa repository then make sure the Dao is not an object but class.
ex:
DAO:
object dao{
@Autowired val repo: jpaRepo = null
}
This won't work (tested). My guess is that since it's defined as an object, gets instantiated at run time with repo as null value, hence won't be able to autowire jpa repo.
Instead declare it as class and mark with @Component:
@Component
class dao{
@Autowired val repo: jpaRepo = null
}
It works since we are letting spring to manage the object creation(@component) that autowires jpa repo properly.
score:1
None of the previous answears worked for me, but after some struggle I could solve it like this:
@Service
class BeanUtil extends ApplicationContextAware {
def setApplicationContext(applicationContext: ApplicationContext): Unit = BeanUtil.context = applicationContext
}
object BeanUtil {
private var context: ApplicationContext = null
def getBean[T](beanClass: Class[T]): T = context.getBean(beanClass)
}
an then the object:
object MyObject {
val myRepository: MyRepository = BeanUtil.getBean(classOf[MyRepository])
}
score:3
axtavt's solution did not work for me, but combining different suggestions from the other answers I think this is the most elegant solution:
object User {
@Autowired val repo: UserRepository = null
def instance() = this
}
@Configuration
class CompanionsConfig {
@Bean def UserCompanion = User.instance
}
<context:component-scan base-package="your-package" />
A few notes:
- Using @Configuration ensures that your companion objects are eagerly autowired
- Using @Bean def avoids having to deal with noisy names Scala gives to the class that implements the companion object
- val works just fine, as mentioned by Dave Griffith
- there is no need for Scala's @BeanProperty, Spring understands Scala properties out of the box (I'm using 3.2.2)
score:4
All that's actually necessary is that you define your object as a class, rather than an object. That way Spring will instantiate it.
@Service
object UserRest extends RestHelper {
@Autowired
@BeanProperty
val userRepository: UserRepository = null;
.....
}
<beans>
.....
<bean id="userRest" class="com.abc.rest.UserRest" >
<!--- this is my attempt to manually wire it --->
<property name="userRepository" ref="userRepository"/>
</bean>
</beans>
Changing the "val" to "var" is unnecessary (Spring uses reflection, which ignores immutability). I'm pretty sure that that @BeanProperty is also unnecessary (Spring will assign to the underlying field, reflectively).
Source: stackoverflow.com
Related Query
- How to use Spring Autowired (or manually wired) in Scala object?
- How can I use a Scala singleton object in Java?
- How to effectively use Scala in a Spring MVC project?
- How to use scala macros to create a function object (to create a Map[String, (T) => T])
- Scala - How to use Java Singleton Object
- How to use a Map instead of Class object to represent data in Scala
- How do I use scala and scalatest to see if a list contains an object with a field matching a specific value
- How do I use builder pattern to return inner object with Scala macros
- How to use configuration in scala play 2.5.8 in an object
- How to use phantom in scala main object
- How can I use a Scala class as the shared root object across class loaders?
- How to use different names when mapping JSON array to Scala object using combinators
- How do we use spring jdbctemplate in scala programming
- How to use mocks in Scala to mock a singleton object
- How to use an Object in a trait by using its type in Scala
- How to use Scala case class from another Object
- How do I use Spring Expression Language for an Array in an annotation with Scala
- In scala macro, how to lift an object and use it in quasiquote at compile time?
- How to use json object from Javascript in Scala to connect with database?
- how to use spring scala to decouple?
- Use a scala companion object for spring controller instead of implementing at the service layer?
- How to use third party libraries with Scala REPL?
- Scala type keyword: how best to use it across multiple classes
- How the get the classOf for a scala object type
- How to use Scala in IntelliJ IDEA (or: why is it so difficult to get a working IDE for Scala)?
- How do I call a Scala Object method using reflection?
- How do I "get" a Scala case object from Java?
- How to use MySQL JDBC driver in an SBT Scala project?
- How to use IntelliJ with Play Framework and Scala
- How to use scala trait with `self` reference?
More Query from same tag
- Linear Regression Apache Spark with Scala not even straight line
- Trouble interpolating RSA signatures between Python and Java/Scala
- Scala - copy fields of a StructType results in 'cannot resolve symbol fields'
- foldLeft, initialize with first operation and skip first
- Both XPath/getChildElements failed to get XML child in XOM
- Scala - Use different equality comparisons/hashing for the same type
- Applying case class to indidual field in a nested form Scala Play
- How do I write a comparator that compares 2 different fields in a collection of objects?
- Option[io.databaker.env.EnvValue], but type F is invariant in type
- How can I write functional and parallelizable code without using large memory?
- Play Framework Ning WS API encoding issue with HTML pages
- Scala: Tail Recursion and ListBuffer
- Finding pairs of sets so that their union has a specific size
- What is the difference between "def" and "val" to define a function
- spark-shell throwing exceptions
- ScalaMock: Can't handle methods with more than 22 parameters (yet)
- Compile scala project with gradle: MissingRequirementError
- Scala (Easy)Mocking default method parameters
- Scala Spark - Split JSON column to multiple columns
- How to create a List from a HTTP response string based on certain conditions?
- In Scala, are semicolons necessary in some situations?
- set of string to be search in another set
- Reusable views in Play! Framework 2.6.2
- Writing a scala method that can accept subclass of RuntimeException
- Display image from MongoDB using reactivemongo in Play2 Scala
- Serialization error in Akka
- How to change the Guardian Actor's default Supervisor Strategy Decider?
- Is the Scala 2.8 collections library a case of "the longest suicide note in history"?
- Scala formatter - show named parameter
- Parsing an order file, grouping by stock symbol and calculating the average order price with quantity