gpt4 book ai didi

java - Autowiring 对象变得为空

转载 作者:行者123 更新时间:2023-12-01 19:56:19 24 4
gpt4 key购买 nike

我正在为我的应用程序使用 Spring Boot。我在 application.properties 文件中定义 JNDI 名称。

当我尝试在下面的类中获取JdbcTemplate时,它的null:

@Configuration
public class DemoClass
{
@Autowired
private JdbcTemplate template;

@Bean
private DataSource getDS(){
return template.getDataSource(); //NPE
}
}

另一类

@Component
public class SecondClass {
@Autowired
private JdbcTemplate template;

public void show(){
template.getDataSource(): // Working Fine
}
}

最佳答案

我不确定默认情况下是否已配置。如果不是,那么也许您可以尝试自己配置它:

@Autowired
DataSoure dataSource;

@Bean
public JdbcTemplate getJdbcTemplate() {
return new JdbcTemplate(dataSource);
}

无论如何,如果您只需要DataSource,我认为它是由Spring Boot自动配置的,因此您可以在需要时直接 Autowiring 它。

关于java - Autowiring 对象变得为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49635512/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com