I have a class that shall contain data which is de-serialized from a JSON file. This data shall be available in my application, so I want to bind it as bean.
To keep the de-serialization logic and and the data structure together, I wanted to put the @Bean
annotated factory method into the data class itself – like this:
@Configuration
public class MyData {
// factory method
@Bean
public static MyData loadMyData(ResourceLoader resourceLoader) throws IOException {
try (InputStream input = resourceLoader.getResource("classpath:data.json").getInputStream()) {
return new ObjectMapper().readValue(input, MyData.class);
}
}
// data structure
private Map<String, DataDetail> details;
// ...
}
However this fails because @ComponentScan
finds two bean definitions now:
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'org.example.MyData' available: expected single matching bean but found 2: myData,loadMyData
I also tried to replace the @Configuration
with @Component
, but the result is the same.
Am I just missing the right annotation on the class, or is it just not possible to place the @Bean
method in the bean class itself?