https://juejin.cn/post/6844903957135884295

1\. 问题

在平时工作中,只要是做Java开发,基本都离不开Spring框架,Spring的一大核心功能就是IOC,它能帮助我们实现自动装配,基本上每天我们都会使用到@Autowired注解来为我们自动装配属性,那么你知道Autowired注解的原理吗?在阅读本文之前,可以先思考一下以下几个问题。

2\. Demo

先按照如下示例搭建一下本文的demo工程

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.1.8.RELEASE</version>
</dependency>

@Configuration
@ComponentScan("com.tiantang.study")
public class AppConfig {
}

public interface UserService {
}

@Service
public class UserServiceImpl implements UserService {
}

public interface OrderService {

	void query();

}

@Service
public class OrderServiceImpl implements OrderService {

	@Autowired
	private UserService userService;

	public void query(){
		System.out.println(userService);
	}
}

public class MainApplication {

	public static void main(String[] args) {
		AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
		OrderService orderService = applicationContext.getBean(OrderService.class);
		orderService.query();
	}
}