Spring Framwork
-
Inversion of Control Container
Aspect-Oriented Programming
Data Access Framework
Spring MVC
Spring Bean
Managed by Spring Container:
Spring beans are created, wired together, and managed by the Spring IoC container.
The container is responsible for the lifecycle of the beans.
Defined in Configuration:
- Beans are usually defined in a Spring configuration file (XML, annotations, or Java-based configuration using
@Configuration
).
- Beans are usually defined in a Spring configuration file (XML, annotations, or Java-based configuration using
Singleton by Default:
- By default, a bean is a singleton in Spring. This means that there is only one instance of the bean per Spring IoC container. You can change the scope to prototype or other scopes if needed.
Dependency Injection:
- Spring beans can have their dependencies injected via constructor, setter methods, or field injection (annotations like
@Autowired
).
- Spring beans can have their dependencies injected via constructor, setter methods, or field injection (annotations like
Define a Bean
Annotation-Based
Annotate the class with
@Component
,@Service
,@Repository
, or@Controller
Use
@Autowired
to inject dependencies
@Component
public class MyBean {
// Bean logic
}
Java Config-Based
- Use
@Configuration
and@Bean
annotations
@Configuration
public class AppConfig {
@Bean
public MyBean myBean() {
return new MyBean();
}
}
Bean Lifecycle
A Spring bean goes through several stages during its lifecycle:
Instantiation: The container creates the bean instance.
Populating Properties: Dependencies are injected.
Post-Initialization:
- Custom initialization using
@PostConstruct
orInitializingBean
interface.
- Custom initialization using
Ready for Use: The bean is available for use in the application.
Destruction: Beans are cleaned up when the container is shut down, using
@PreDestroy
orDisposableBean
interface.
Example:
Bean Definition:
@Component
public class HelloWorld {
public String sayHello() {
return "Hello, Spring Bean!";
}
}
Main Application:
@SpringBootApplication
public class SpringApp {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(SpringApp.class, args);
HelloWorld helloWorld = context.getBean(HelloWorld.class);
System.out.println(helloWorld.sayHello());
}
}
In this example:
The
HelloWorld
class is a Spring Bean managed by the IoC container.The
@Component
annotation tells Spring to manage this class as a bean.
Spring beans enable the development of loosely coupled, modular, and testable applications. They are a fundamental concept in the Spring framework for building scalable and maintainable software.