简体   繁体   中英

Scanning @Configuration beans in Spring 4

Hy

I am upgrading my web app from Spring 3.1 to 4.1.8 but having issues. My code has not changed (only my pom.xml)

I have a configuration bean in my main context that looks like:

@Configuration
public class StorableServiceConfiguration {
    ...
    @Bean 
    public StorableService<Template, Long> templateService(ITemplateJpaDao dao) {
        return new DaoService<Template, Long>(Template.class, dao);
    }
}

And obviously somewhere else in my web app, I have this statement:

@Autowired
@Qualifier("templateService")
private StorableService<Template, String> templateService;

Now this all worked fine with Spring 3.1.1 but after updating the version to 4.1.8, I am getting this error:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [w.wexpense.service.StorableService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=templateService)}

Anybody got a clue?

I read somewhere that there was a change in Spring 4 on how the context:component-scan behave regarding the @Configuration annotation but can't remember what. Is anybody aware of that?

Thanks

Spring 4 autowire beans using Java generics as form of @Qualifier .

So you have a Bean @Autowired with StorableService<Template, String> but in your @Configuration class your @Bean declares StorableService<Template, Long> .

If you want a StorableService<Template, String> instance you should create another @Bean at your @Configuration class, for example:

@Bean 
public StorableService<Template, String> templateService(ITemplateJpaDao dao) {
    return new DaoService<Template, String>(Template.class, dao);
}

and autowire it without the @Qualifier annotation:

@Autowired
private StorableService<Template, String> templateService;

Spring 4 will inject it perfectly. Look at this blog post to see this new feature of Spring 4.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM