spring配合scala时,@Autowired的一个问题

今天在用spring配合scala时,遇到了一个关于@Autowired的问题,主要报错信息如下:

Caused by: java.lang.NoSuchMethodException: com.zk_chs.xxxxx.....<init>()
	at java.lang.Class.getConstructor0(Class.java:3082) ~[na:1.8.0_73]
	at java.lang.Class.getDeclaredConstructor(Class.java:2178) ~[na:1.8.0_73]
	at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:80) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
	... 52 common frames omitted

根据报错信息来看的话,是因为构造函数的问题,那么,一定是scala编译时做了我们不知道的修改。我的代码:

/**
  * Created by zk_chs on 16/4/12.
  */
@Configuration
@EnableTransactionManagement
class MyBatisConfig @Autowired() (dataSource: DataSource) extends TransactionManagementConfigurer{

  @Bean
  override def annotationDrivenTransactionManager : PlatformTransactionManager = {
    new DataSourceTransactionManager(dataSource)
  }

  omitted......

}

在这里,我们的scala类在构造对象时,需要传入DataSource,这里采用了@Autowired,然后就会发生上面的错误,但是,如果在@Configuration中没有添加@Bean注解的话,那么又不会发生报错,例如下面的代码:

/**
  * Created by zk_chs on 16/4/12.
  */
@Service
class ApService @Autowired() (private val apMapper: ApMapper) {

  def getById (id: Int) = {
    apMapper selectByPrimaryKey id
  }

}

虽然不知道为什么,但是解决方式还是找到了,如果读者有兴趣的话,可以自己反编译生成的class文件,到时候找到原因分享给大家。这里可以使用如下方式对DataSource进行定义:

@Configuration
@EnableTransactionManagement
class MyBatisConfig extends TransactionManagementConfigurer{

  @Autowired
  private val dataSource: DataSource = null

  @Bean
  override def annotationDrivenTransactionManager : PlatformTransactionManager = {
    new DataSourceTransactionManager(dataSource)
  }

  omitted......

}

我们将dataSource变成类的属性,而不是构造函数的参数,val和var都可以,但都需要初始化,这样一来,便能解决掉构造函数的问题了。

猜你喜欢

转载自zk-chs.iteye.com/blog/2290572
今日推荐