1
votes

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
Honestly I'm not comfortable with you using an XML file for this; have you attempted to do this with a properties file instead?Makoto
@Makoto no I haven't I'll try to do it with properties file.Renaud is Not Bill Gates
why are you not leveraging your POJO with the properties file itselfMavericks

1 Answers

1
votes

There are two problems with the code.

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

@ImportResource imports beans definitions, usually in conjunction with XML Spring configuration.

To load property values for @Value from a configuration file, use @PropertySource.

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

#{sample.findAll} is a SpEL expression. It asks Spring to evaluate sample.findAll, using sample as a bean. Since there is no bean of that name in the context, Spring rightly complains that there is no such bean.

To load the value of the property sample.findAll from a configuration source, use the syntax ${sample.findAll}.


The following code will work:

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