简体   繁体   中英

Autowiring doesn't work in Spring 4

I have the following source example which works in Spring 3.2.6 but doesn't work in 4.0.1

public interface RunTest<T extends Number> {
void run(T number);

}

public class BasicRunTest implements RunTest<Integer>{

@Override
public void run(Integer number) {
}

}

@Component
public class BeanTest  {
@Autowired
private RunTest<Number> runTest; 
}

If I run the application I get the exception:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.test.RunTest] 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)}

It is a new Spring Feature: Spring now treats generic types as a form of qualifier when injecting Beans - or in other words: autowire pay attention to the generic type!

You have BasicRunTest implements RunTest<Integer> (Integer) and ask spring for @Autowire prive RunTest<Number> runTest; (Number) - that is not compatible!

try

private RunTest<? extends Number> runTest;

(That it worked with Spring 3.x, is more or less a bug, because your code break the generic constraint)

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