新建两个测试类 ,A是一个公共接口
@Service
public class AImpl1 implements A {
@Override
public void zhuru() {
System.out.println("AImpl1");
}
}
@Service
public class AImpl2 implements A {
@Override
public void zhuru() {
System.out.println("AImpl2");
}
}
Resource测试类
@RestController
@RequestMapping("/")
public class ResTest {
@Resource
private AImpl1 AImpl2;
@Resource
private AImpl2 AImpl1;
@Resource
private C c;
@RequestMapping("/say")
public String say(){
AImpl1.zhuru();
AImpl2.zhuru();
return "over";
}
}
程序报错
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'resTest': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'AImpl2' is expected to be of type [com.xxxx.Resource.AImpl1] but was actually of type [com.xxxx.Resource.AImpl2]
不能将AImpl2注入AImpl1中。
修改代码:
控制台输出结果:
可以看出@Resource是使用变量名来注入bean。
Autowired测试类
@RestController
@RequestMapping("/AutoTest")
public class AutoTest {
@Autowired
private AImpl1 AImpl2;
@Autowired
private AImpl2 AImpl1;
@RequestMapping("/say")
public String say(){
AImpl1.zhuru();
AImpl2.zhuru();
return "over";
}
}
控制台输出结果:
@Autowired是使用对象类型来注入bean
如果使用@Autowired 在接口上,并且接口有多个实现类,就会报错,如下:
最重要的一件事情!!!!!!
使用@Resource注解,不是所有的变量名都是首字母小写,如果前两位及以上都是大写,那么变量名就是类名
这段文字来源16楼:https://www.cnblogs.com/xrq730/p/5313412.html
如果类的名字是两个或以上连续的大写字母开头,bean的名字会与类名是一样的,不会首字母变小写
spring源码:public class AnnotationBeanNameGenerator implements BeanNameGenerator {
@Override
public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
if (definition instanceof AnnotatedBeanDefinition) {
String beanName = determineBeanNameFromAnnotation((AnnotatedBeanDefinition) definition);
if (StringUtils.hasText(beanName)) {
// Explicit bean name found.
return beanName;
}
}
// Fallback: generate a unique default bean name.
return buildDefaultBeanName(definition, registry);
}
protected String buildDefaultBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
return buildDefaultBeanName(definition);
}
protected String buildDefaultBeanName(BeanDefinition definition) {
String beanClassName = definition.getBeanClassName();
Assert.state(beanClassName != null, "No bean class name set");
String shortClassName = ClassUtils.getShortName(beanClassName);
return Introspector.decapitalize(shortClassName);
}
转到jdk
public static String decapitalize(String name) {
if (name == null || name.length() == 0) {
return name;
}
if (name.length() > 1 && Character.isUpperCase(name.charAt(1)) &&
Character.isUpperCase(name.charAt(0))){
return name;
}
char chars[] = name.toCharArray();
chars[0] = Character.toLowerCase(chars[0]);
return new String(chars);
}