Spring Boot中Unsatisfied Dependency Exception异常求助
Fixing Unsatisfied Dependency Exception in Spring Boot for XML Properties
Hey there, let's troubleshoot that Unsatisfied Dependency Exception you're running into with Spring Boot. I've looked at your code and config, and here's what's going wrong and how to fix it:
Why You're Seeing This Error
You've got two key issues here:
- Wrong expression in
@Value: The#{sample.findAll}syntax is Spring Expression Language (SpEL), which tells Spring to look for a bean namedsampleand fetch itsfindAllproperty. You don't have a bean namedsample—you have a properties entry with that key, so this won't work. - Incorrectly loading the XML properties file:
@ImportResourceis meant for loading Spring bean definition XML files, not raw properties XML. Spring can't parse your properties file this way, so those entries never make it into the Spring environment.
Solution 1: Load XML Properties with PropertySourcesPlaceholderConfigurer
If you want to keep using the XML format for your properties (great for handling complex SQL with special characters via CDATA), create a bean to load the file properly:
@Configuration public class SampleFindAllConfig { // This bean tells Spring to load your XML properties file @Bean public static PropertySourcesPlaceholderConfigurer propertyConfigurer() { PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer(); // Point to your XML properties file Resource resource = new ClassPathResource("sql/find-all-sample-native-query.xml"); configurer.setLocation(resource); configurer.setFileEncoding("UTF-8"); return configurer; } // Use ${...} to pull the property from the Spring environment @Value("${sample.findAll}") private String findAllQuery; // Optional: Expose the query as a bean if you need to inject it elsewhere @Bean public String sampleFindAllQuery() { return findAllQuery; } }
Solution 2: Switch to a Regular .properties File (Simpler)
If your SQL doesn't need CDATA, converting the XML to a standard .properties file is easier. Create src/main/resources/sql/find-all-sample-native-query.properties:
sample.findAll=The SQL query goes here
Then update your config class to load it with @PropertySource:
@Configuration @PropertySource("classpath:sql/find-all-sample-native-query.properties") public class SampleFindAllConfig { @Value("${sample.findAll}") private String findAllQuery; // Your other beans or logic here }
Quick Checks to Avoid Future Issues
- Double-check the file path:
classpath:sql/...means the file must live insrc/main/resources/sql/(orsrc/test/resources/for tests). - If your SQL has line breaks or special characters, stick with the XML properties file—CDATA handles these without needing extra escaping.
内容的提问来源于stack exchange,提问作者Renaud is Not Bill Gates
相关产品推荐
相关产品推荐

