相同点:
@AutoWired和@Resource注解都是从Spring容器中取出相应的bean对象,自动装配。
不同点:
@AutoWired:
默认根据类型进行自动装配,依赖的对象必须存在,如果允许为null值,需要加required=false,即@AutoWired(required=false);若要通过名称装配可以配合@Qualifier注解;
@Resource:
默认根据名称进行自动装配,由nane属性指定名称,代码如下:
//定义一个Animal接口
public interface AnimalService {
//定义一个eat的抽象方法,由子类去重写
void eat();
}
//定义Cat类实现AnimalService接口
@Service
public class CatServiceImpl implements AnimalService {
//重写eat方法
@Override
public void eat() {
System.out.println("猫喜欢吃鱼");
}
}
//定义Dog类实现AnimalService接口
@Service
public class DogServiceImpl implements AnimalService{
//重写eat方法
@Override
public void eat() {
System.out.println("狗喜欢吃骨头");
}
}
//单元测试
@SpringBootTest
public class DemoApplicationTests {
/**
* 此处若只写@AutoWired注解,会报错,因为AnimalService接口有两个实现类,默认根据
类型匹配会冲突,因此需要配合@Qualifier注解使用名称定位到具体bean,注意value属性
首字母要小写,前提是@Service注解没有配置value属性,否则要与其保持一致。
*/
@Autowired
@Qualifier(value = "catServiceImpl")
//@Resource(name="catServiceImpl")也可使用该注解代替上面两个注解,效果完全一样。
private AnimalService animalService;
@Test
void contextLoads() {
animalService.eat();
}
}
看下执行效果:
2020-06-05 17:05:57.531 INFO 14521 --- [ main] com.example.demo.DemoApplicationTests : Starting DemoApplicationTests on FinupdeMacBook-Pro.local with PID 14521 (started by finup in /Users/configSoftWare/IdeaProjects/demo)
2020-06-05 17:05:57.533 INFO 14521 --- [ main] com.example.demo.DemoApplicationTests : No active profile set, falling back to default profiles: default
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
2020-06-05 17:05:59.479 INFO 14521 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-06-05 17:05:59.576 INFO 14521 --- [ main] o.s.b.a.w.s.WelcomePageHandlerMapping : Adding welcome page template: index
2020-06-05 17:05:59.865 INFO 14521 --- [ main] com.example.demo.DemoApplicationTests : Started DemoApplicationTests in 2.633 seconds (JVM running for 3.702)
猫喜欢吃鱼