← Back

Bean

//Spring 自动把 UserService 注入进来,不需要手动传参或 new
@Service
public class OrderService {
    @Autowired
    private UserService userService;
	}

IOC(Spring Container)—called Bean

How a Bean is created

  1. Annotation-based (most common)

Spring scans and registers them as Beans.

@Service
@Component
@Controller
@Repository
  1. 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:

What Bean really gives you (core value)

  1. Dependency Injection (DI)

Instead of:

CouponService service = new CouponService();

You write:

@Autowired
private CouponService service;

Spring injects dependencies automatically.

  1. Loose coupling
@Autowired
private PaymentService paymentService;

You don’t care which implementation is used.

  1. Lifecycle management

full lifecycle:

  1. Bean definition loaded

  2. Bean instantiated实例化 (new)

  3. Dependency injection

  4. Initialization (@PostConstruct)

  5. Ready for use

  6. Destroy (@PreDestroy)

  7. AOP support (very important)

Because Spring controls Beans, it can add:

Without Beans → these don’t work

Bean Scope

  1. Default is singleton

    @Service
    • only ONE instance in the container
    • shared everywhere
  2. Prototype

    	@Scope("prototype")
    • new object every time you request
  3. Other scopes (web)

    • request
    • session

Bean Injection methods

  1. Field字段 injection

    @Autowired
    private CouponService service;
  2. Constructor injection (recommended in real projects)—easier testing, immutable

    private final CouponService service;
    public OrderService(CouponService service) {
    this.service = service;
    }
  3. Setter injection (rare)