How does autowiri...
How does autowiri...
Autowiring in Spring is a mechanism that allows you to inject the bean dependencies automatically without the need for explicit bean wiring in XML configuration files or Java-based configuration. It is part of the broader concept of Dependency Injection (DI) provided by the Spring Framework, which is a way to achieve Inversion of Control (IoC) for managing object creation and binding.
When you declare a bean in the Spring context, you can specify that Spring should automatically wire your beans together by inspecting the contents of the ApplicationContext. The @Autowired
annotation is commonly used to enable autowiring.
There are several modes of autowiring in Spring:
No Autowiring (default): No autowiring is done by default. You have to manually wire the beans using references.
byName: Autowiring by property name. If a bean's name matches a property name of another bean, it will be wired automatically.
byType: Autowiring by property type. If there is exactly one bean of the property type in the context, it will be wired automatically.
constructor: Similar to byType, but applies to constructor arguments. If there is exactly one bean of the constructor argument type in the context, it will be wired automatically.
autodetect: Deprecated in newer versions of Spring. It used to autowire by constructor if possible; otherwise, it would autowire by type.
The @Autowired
annotation can be used on fields, setter methods, and constructors. When you use @Autowired
, Spring will try to match the bean by type. If there are multiple beans of the same type, you can use the @Qualifier
annotation to specify which bean should be wired.
Spring resolves @Autowired
entries by first looking for matching beans in the context that fit the criteria (name, type, qualifier). If the framework finds a match, it will inject that bean into the annotated field or method...
expert
Gợi ý câu hỏi phỏng vấn
Explain the difference between context:annotation-config vs context:component-scan
Chưa có bình luận nào