请求从入门讲解Spring Bean、Autowired及二者协同工作(附示例)
Hey there! I totally get why you're confused—most tutorials skip the basics and throw jargon around. Let's start from zero, with plain language and concrete examples to make this click.
一、什么是Spring Bean?
Think of the Spring framework as a smart toolbox. A Spring Bean is just a regular Java object that lives inside this toolbox. The key difference from objects you create with new is:
- Spring creates the Bean for you when your application starts.
- Spring manages its entire lifecycle (when it's created, when it's destroyed, etc.).
- Any part of your app that needs this object can grab it from the toolbox instead of making a new one.
To turn a Java class into a Bean, you just add a special annotation like @Component, @Service, @Repository, or @Controller. These annotations tell Spring: "Hey, this class is a Bean—put it in your toolbox!"
二、什么是Autowiring(自动装配)?
Autowiring is Spring's way of handing you the exact tool (Bean) you need without you having to dig through the toolbox yourself.
Without autowiring, if you needed a UserRepository Bean in your UserService, you'd have to:
- Find the Spring toolbox (application context).
- Manually pull out the UserRepository Bean from it.
- Assign it to a variable in your UserService.
With autowiring (using the @Autowired annotation), you just tell Spring: "I need a Bean of type X here—please give it to me." Spring does all the digging and assigning for you automatically.
三、二者如何协同工作?
Here's the step-by-step flow when your Spring app starts:
- Spring scans your code for classes with Bean annotations (
@Service,@Repository, etc.). - It creates an instance of each of these classes and stores them in its toolbox (application context).
- Then, Spring looks for any
@Autowiredannotations in your Beans. - For each
@Autowiredfield/method/constructor, Spring finds a matching Bean in the toolbox and "injects" it into the spot you marked. - Now your Beans can collaborate with each other without you having to manually connect them.
四、具体示例(拒绝笼统说明!)
Let's build a tiny app to see this in action.
1. 创建UserRepository Bean(数据层)
这个Bean负责模拟获取用户数据:
import org.springframework.stereotype.Repository; // @Repository告诉Spring这是一个数据层的Bean @Repository public class UserRepository { // 模拟从数据库获取用户信息 public String getUserById(String userId) { return "用户" + userId + ": 张三"; } }
发生了什么? 应用启动时,Spring会创建UserRepository的实例,并把它存到自己的上下文(工具盒)里。
2. 创建UserService Bean(业务层)
这个Bean需要用到UserRepository来完成工作——我们用@Autowired自动获取它:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; // @Service告诉Spring这是一个业务层的Bean @Service public class UserService { // @Autowired告诉Spring:"我这里需要一个UserRepository类型的Bean,帮我注入进来!" @Autowired private UserRepository userRepository; public String getUserName(String userId) { // 直接使用注入进来的userRepository,不需要自己创建实例! return userRepository.getUserById(userId); } }
发生了什么? Spring看到userRepository字段上的@Autowired注解后,会去上下文里找到之前创建的UserRepository Bean,把它赋值给这个字段。现在UserService可以直接调用UserRepository的方法了。
3. 测试应用
启动Spring上下文,验证自动装配是否生效:
import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class SpringDemoApp { public static void main(String[] args) { // 启动Spring上下文,扫描你的包下的所有Bean AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.scan("com.yourpackage"); // 替换成你实际的包名 context.refresh(); // 从上下文取出UserService Bean UserService userService = context.getBean(UserService.class); // 调用方法测试自动装配效果 System.out.println(userService.getUserName("001")); } }
预期输出:
用户001: 张三
这证明UserRepository已经成功注入到UserService中——它们不需要我们手动关联就能协同工作了!
补充小知识点
- 默认单例模式: Spring默认创建的Bean是单例的——也就是说,应用里所有用到这个Bean的地方,用的都是同一个实例,既节省内存又保证一致性。
- 同类型多Bean场景: 如果有两个
UserRepository类型的Bean,@Autowired会报错。这时候可以用@Qualifier("beanName")指定要注入的Bean名称,或者用@Primary标记优先选择的Bean。
内容的提问来源于stack exchange,提问作者shelo

