【问题标题】:spring boot: unable to autowire bean, but the bean is defined for surespring boot:无法自动装配bean,但确定定义了bean
【发布时间】:2015-01-08 19:34:56
【问题描述】:

我写了一个spring boot小程序,需要使用jdbcTemplate连接数据库。存在 JDBC 驱动程序,我在 application.properties 中设置了所有内容:

spring.datasource.url=jdbc:oracle:thin:@servername:1521:foo
spring.datasource.username=guesswho
spring.datasource.password=iwonttell
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver

当我通过打开 localhost:8080/beans 让 spring boot 执行器显示 bean 时,我可以看到我的类需要 bean ...

1:Object
bean:"mybean"
scope:"singleton"
type:"de...."
resource:"file [C:/....class]"
dependencies:Array[1]
0:"jdbcTemplate"

...我可以看到 bean 已定义:

56:Object
bean:"jdbcTemplate"
scope:"singleton"
type:"org.springframework.jdbc.core.JdbcTemplate"
resource:"class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$JdbcTemplateConfiguration.class]"
dependencies:Array[0]

这是我的代码,它显示了我尝试过的所有三种自动装配变体,但它们都不起作用

public class myBean implements IMyBean {
  @Autowired
  private JdbcTemplate jdbcTemplate;

  @Autowired
  public myBean(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
  }

  @Autowired
  public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
  }

  @Override
  public foo searchDb(String for) {
    String sql = "SELECT bar FROM ...";

    jdbcTemplate.query( sql, ...

在 jdbcTemplate.query 的最后一行发生了 NPE。

我想我看不到森林的树木。我检查了 stackoverflow 提供的建议答案(例如spring-boot properties not @Autowired),但我认为它们与我的问题不符。衷心感谢您的帮助...

【问题讨论】:

  • 你能怎么stacktrace,还是只是给出了一个空指针异常?
  • 当我在使用 jdbcTemplate 的类上运行方法时抛出 npe
  • 你能把“myBean”“JdbcTemplate”的代码和你使用“mybean”的地方显示出来吗?使用一些代码会更容易
  • 当然。 JdbcTemplate 由 Spring JDBC 提供,所以我将跳过它。
  • 以及调用 myBean.searchDb 的类?另外我假设“myBean”或“IMyBean”由“@Service”或“@Component”注释

标签: spring spring-mvc autowired


【解决方案1】:

问题是由一个忘记的注释引起的:@AutoWired 丢失了,因此我有两个实例。一个配置正确并包含 jdbcTemplate,另一个有一个空 jdbcTemplate。 我检查了第一个,但没有使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-06
    • 2016-09-27
    • 2018-04-13
    • 2016-09-10
    • 2012-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多