Junior — Middle
What methods and approaches exist for defining and initializing beans in the Spring Framework?
sobes.tech AI
Answer from AI
In the Spring Framework, beans are objects managed by the Spring container. The main ways to define and initialize beans:
- XML configuration — the traditional method, where beans are described in an XML file using the
<bean>tag. For example:
<bean id="myBean" class="com.example.MyClass" />
- Annotations — a more modern approach:
@Component— marks a class as a bean.@Service,@Repository,@Controller— specialized components.@Bean— used in configuration class methods with@Configurationto create beans.
Example:
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyServiceImpl();
}
}
@Component
public class MyComponent {
// the bean will be created automatically
}
-
Java-based configuration — creating beans through classes with the
@Configurationannotation and methods with@Bean. -
Automatic component scanning — using
@ComponentScan, Spring automatically finds classes with component annotations and registers them as beans.
Bean initialization can occur through constructors, setters, or methods annotated with @PostConstruct.
Thus, modern projects more often use annotations and Java configuration, while XML is rarely used.