文章目录
前言
这位BAT大佬写的Leetcode刷题笔记,让我offer拿到手软
1.@Autowired的默认装配
我们都知道在spring中@Autowired注解,是用来自动装配对象的。通常,我们在项目中是这样用的:
package com.sue.cache.service;
import org.springframework.stereotype.Service;
@Service
public class TestService1 {
public void test1() {
}
}
package com.sue.cache.service;
import org.springframework.stereotype.Service;
@Service
public class TestService2 {
@Autowired
private TestService1 testService1;
public void test2() {
}
}
没错,这样是能够装配成功的,因为默认情况下spring是按照类型装配的,也就是我们所说的byType
方式。
此外,@Autowired注解的required
参数默认是true,表示开启自动装配,有些时候我们不想使用自动装配功能,可以将该参数设置成false。
2.相同类型的对象不只一个的时候
上面byType
方式主要针对相同类型的对象只有一个的情况,此时对象类型是唯一的,可以找到正确的对象。
但如果相同类型的对象不只一个时,会发生什么?
在项目的test目录下,建了一个同名的类TestService1:
package com.sue.cache.service.test;
import org.springframework.stereotype.Service;
@Service
public class TestService1 {
public void test1() {
}
}
重新启动项目时:
Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'testService1' for bean class [com.sue.cache.service.test.TestService1] conflicts with existing, non-compatible bean definition of same name and class [com.sue.cache.service.TestService1]
结果报错了,报类类名称有冲突,直接导致项目启动不来。