Unsatisfied Dependency Exception in Spring boot

时间:2018-04-18 17:52:41

标签: java spring spring-boot

I have a properties XML file as following :

<?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>

And a config file as following :

@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;
    }
}

I'm injecting the Bean in the DAO class as following :

@Inject
private String findAllAnomalieNativeQuery;

But I get this error when I run my application :

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?

How can I solve this ?

1 个答案:

答案 0 :(得分:1)

代码存在两个问题。

  

问题1 :使用@PropertySource加载@Value

的属性值

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

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

  

问题2 :使用${...}语法

引用属性

#{sample.findAll}是一个SpEL表达式。它要求Spring使用sample.findAll作为bean来评估sample。由于上下文中没有该名称的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;
    }
}