Java Spring中的Kotlin setter依赖项注入
我正在学习Java Spring中的Kotlin setter依赖项注入,java,spring,kotlin,Java,Spring,Kotlin,我正在学习spring数据,因为我也在学习kotlin,所以我决定在spring学习期间与kotlin一起工作。所以我想问我们如何在kotlin中实现setter依赖注入?在Java中,我们可以如下所示 @Component public class StudentDaoImp { public DataSource dataSource; public JdbcTemplate jdbcTemplate; public DataSource getDataSour
spring数据
,因为我也在学习kotlin
,所以我决定在spring学习期间与kotlin一起工作。所以我想问我们如何在kotlin中实现setter
依赖注入?在Java中,我们可以如下所示
@Component
public class StudentDaoImp {
public DataSource dataSource;
public JdbcTemplate jdbcTemplate;
public DataSource getDataSource() {
return dataSource;
}
@Autowired
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
}
这是我的spring.xml
文件
<?xml version="1.0" encoding="UTF-8"?>
<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"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.h2.Driver" />
<property name="url" value="jdbc:h2:~/test" />
</bean>
<context:component-scan base-package="com.package.*" />
</beans>
那我就例外了
原因:kotlin.UninitializedPropertyAccessException:lateinit
属性数据源尚未初始化
我知道这个异常,因为我在autowired
发生之前使用了dataSource
。所以我也试过这个
@Autowired
fun setDataSource(dataSource: DataSource) {
this.jt = JdbcTemplate(dataSource)
}
这也是一个错误,因为JVM在幕后已经有了这个签名
那么如何使用dataSource
参数初始化JdbcTemplate
注意:我只想要代码端示例/解决方案。我知道XML解决方案。就像在Java中一样,您不能使用在实例化时实例化后注入的属性。在Java中,当您执行等效操作时,您会得到一个
NullPointerException
,例如
@Autowired
private Datasource datasource;
private JdbcTemplate jt = new JdbcTemplace(dataSource);
但您可以让Spring在注入所有内容后调用您选择的方法:
lateinit var jt: JdbcTemplate
@PostConstruct
fun initAfterAutowireIsDone() {
jt = JdbcTemplate(dataSource)
}
还有一个初始化bean
接口,可以用来代替注释。在Java中也是如此
Kotlin中的另一个选项是在确保在实例化时不访问惰性属性时使用它
val jt: JdbcTemplate by lazy { JdbcTemplate(dataSource) }
虽然我认为ZAPL答案是正确的,但我也建议您考虑构造函数参数注入:
@Component
class StudentDao @Autowired constructor(
private val dataSource: DataSource
) {
private val jt = JdbcTemplate(dataSource)
}
通过这种方式,您可以获得不可修改的变量,而不会出现初始化延迟的警告
另外,如果只需要dataSource
变量来初始化jt
,则可以从构造函数中删除val
键
@Component
class StudentDao @Autowired constructor(
private val dataSource: DataSource
) {
private val jt = JdbcTemplate(dataSource)
}