gpt4 book ai didi

java - Spring boot 中依赖关系不满足异常

转载 作者:行者123 更新时间:2023-11-30 06:12:36 24 4
gpt4 key购买 nike

我有一个属性 XML 文件,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<entry key="sample.findAll">
<![CDATA[
The SQL query goes here
]]>
</entry>
</properties>

配置文件如下:

@ImportResource("classpath:sql/find-all-sample-native-query.xml")
@Configuration
public class SampleFindAllConfig {

@Value("#{sample.findAll}")
private String findAllQuery;

@Bean
public String findAllSampleNativeQuery() {
return findAllQuery;
}
}

我将 Bean 注入(inject)到 DAO 类中,如下所示:

@Inject
private String findAllAnomalieNativeQuery;

但是当我运行我的应用程序时出现此错误:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sampleDAO': Unsatisfied dependency expressed through field 'findAllSampleNativeQuery'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sampleFindAllConfig': Unsatisfied dependency expressed through field 'findAllQuery'; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'sample' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?

我该如何解决这个问题?

最佳答案

代码有两个问题。

Problem 1: Use @PropertySource to load with property values with @Value

@ImportResource 导入 bean 定义,通常与 XML Spring 配置结合使用。

要从配置文件加载 @Value 的属性值,请使用 @PropertySource

Problem 2: Reference properties using the ${...} syntax

#{sample.findAll} 是 SpEL 表达式。它要求 Spring 使用 sample 作为 bean 来评估 sample.findAll。由于上下文中不存在同名的 bean,Spring 正确地提示不存在这样的 bean。

要从配置源加载属性 sample.findAll 的值,请使用语法 ${sample.findAll}

<小时/>

以下代码将起作用:

@Configuration
@PropertySource("classpath:sql/find-all-sample-native-query.xml")
public class SampleFindAllConfig {
@Value("${sample.findAll}")
private String findAllQuery;

@Bean
public String findAllSampleNativeQuery() {
return findAllQuery;
}
}

关于java - Spring boot 中依赖关系不满足异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49906051/

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