Spring Bean – это ОБЪЕКТ, который управляется Spring-контейнером.
🚩Пример: Обычный класс vs. Bean
Обычный класс (НЕ Bean)
class Car {
void drive() {
System.out.println("Машина едет...");
}
}public class Main {
public static void main(String[] args) {
Car car = new Car(); // Создание обычного объекта вручную
car.drive();
}
}Bean в Spring
import org.springframework.stereotype.Component;
@Component // Аннотация говорит Spring, что этот класс – Bean
class Car {
void drive() {
System.out.println("Spring-машина едет...");
}
}
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
Car car = context.getBean(Car.class); // Получаем объект из Spring-контейнера
car.drive();
}
}
Ставь 👍 и забирай 📚 Базу знаний