
🏡Java码农探花:
🔥 推荐专栏:<springboot学习>
🛸学无止境,不骄不躁,知行合一
前言
在上一篇文章中,讲诉了SpringIoC的Bean装配,但是对于如何进行获取,也就是Bean之间的依赖还未讲诉,下面开始讲诉依赖注入(Dependency Injection,DI)以及如何使用属性文件。涉及主要注解@Autowired、@Primary、@Quelifier、@PropertySource和@ConfigurationProperties。
一、🌕依赖注入
例:人类(Person)有时候利用一些动物(Animal)去完成一些事情,比方说狗(Dog)是用来看门的,猫(Cat)是用来抓老鼠的, 鹦鹉(Paηot)是用来迎客的……于是做一些事情就依赖于那些可爱的动物。假设现在需要用狗狗来看门。
//定义人类接口
public interface Person {
void service();
void setAnimal(Animal animal);
}
//定义动物接口
public interface Animal {
void user();
}
//定义狗
@Component
public class Dog implements Animal {
@Override
public void user() {
System.out.println("狗【" + Dog.class.getSimpleName() + "】是用来看门的");
}
}
//定义年轻人
@Component
public class YoungPerson implements Person {
@Autowired
private Animal animal = null;
@Override
public void service() {
this.animal.user();
}
@Override
public void setAnimal(Animal animal) {
this.animal = animal;
}
}
//定义配置类
@Configuration
@ComponentScan("com.dragon.restart")//所有的包和类都在restart下
public class AppConfig {
}
![]()

本文详细介绍了Java中SpringBoot中的依赖注入机制,包括@Autowired注解的使用、歧义性的处理(Qualifier和Primary)、以及如何通过属性文件和@ConfigurationProperties简化配置。
最低0.47元/天 解锁文章
1081

被折叠的 条评论
为什么被折叠?



