- Bean 本质就是“被 Spring 容器(IOC container)管理的对象”。 Bean = 普通 Java 对象 + 交给 Spring 管理生命周期和依赖关系
- Spring creates it, manages it, injects it where needed
//Spring 自动把 UserService 注入进来,不需要手动传参或 new
@Service
public class OrderService {
@Autowired
private UserService userService;
}IOC(Spring Container)—called Bean
- The container is like a factory + warehouse of objects.
- Spring scans your code, Finds classes with annotations, Creates objects, Stores them in a map (Bean container)
Example internal structure: BeanContainer: "couponService" -> CouponService instance "orderService" -> OrderService instance
How a Bean is created
- Annotation-based (most common)
Spring scans and registers them as Beans.
@Service
@Component
@Controller
@Repository- Configuration class
Manually define the Bean.
@Configuration
public class AppConfig {
@Bean
public CouponService couponService() {
return new CouponService();
}
}3.Third-party libraries
Spring Boot auto-config creates Beans for you:
- DataSource
- RedisTemplate
- KafkaTemplate
What Bean really gives you (core value)
- Dependency Injection (DI)
Instead of:
CouponService service = new CouponService();You write:
@Autowired
private CouponService service;Spring injects dependencies automatically.
- Loose coupling
@Autowired
private PaymentService paymentService;You don’t care which implementation is used.
- Lifecycle management
full lifecycle:
Bean definition loaded
Bean instantiated实例化 (new)
Dependency injection
Initialization (@PostConstruct)
Ready for use
Destroy (@PreDestroy)
AOP support (very important)
Because Spring controls Beans, it can add:
- transactions (
@Transactional) - logging
- security
Without Beans → these don’t work
Bean Scope
Default is singleton
@Service- only ONE instance in the container
- shared everywhere
Prototype
@Scope("prototype")- new object every time you request
Other scopes (web)
- request
- session
Bean Injection methods
Field字段 injection
@Autowired private CouponService service;Constructor injection (recommended in real projects)—easier testing, immutable
private final CouponService service; public OrderService(CouponService service) { this.service = service; }Setter injection (rare)