1. Información general
Este artículo de Spring Framework demostrará el uso de anotaciones relacionadas con la inyección de dependencia, a saber, las anotaciones @Resource , @Inject y @Autowired . Estas anotaciones proporcionan a las clases una forma declarativa de resolver dependencias. Por ejemplo:
@Autowired ArbitraryClass arbObject;
en lugar de instanciarlos directamente (la forma imperativa), por ejemplo:
ArbitraryClass arbObject = new ArbitraryClass();
Dos de las tres anotaciones pertenecen al paquete de extensión de Java: javax.annotation.Resource y javax.inject.Inject . La anotación @Autowired pertenece al paquete org.springframework.beans.factory.annotation .
Cada una de estas anotaciones puede resolver dependencias ya sea mediante inyección de campo o mediante inyección de setter. Se utilizará un ejemplo simplificado pero práctico para demostrar la distinción entre las tres anotaciones, según las rutas de ejecución tomadas por cada anotación.
Los ejemplos se centrarán en cómo utilizar las tres anotaciones de inyección durante las pruebas de integración. La dependencia requerida por la prueba puede ser un archivo arbitrario o una clase arbitraria.
2. El @Resource A nnotation
La anotación @Resource es parte de la colección de anotaciones JSR-250 y está empaquetada con Jakarta EE. Esta anotación tiene las siguientes rutas de ejecución, enumeradas por precedencia:
- Coincidir por nombre
- Coincidencia por tipo
- Partido por clasificatorio
Estas rutas de ejecución son aplicables tanto al setter como a la inyección de campo.
2.1. Inyección de campo
La resolución de dependencias por inyección de campo se logra anotando una variable de instancia con la anotación @Resource .
2.1.1. Coincidir por nombre
La prueba de integración que se usa para demostrar la inyección de campos de coincidencia por nombre se enumera a continuación:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration( loader=AnnotationConfigContextLoader.class, classes=ApplicationContextTestResourceNameType.class) public class FieldResourceInjectionIntegrationTest { @Resource(name="namedFile") private File defaultFile; @Test public void givenResourceAnnotation_WhenOnField_ThenDependencyValid(){ assertNotNull(defaultFile); assertEquals("namedFile.txt", defaultFile.getName()); } }
Repasemos el código. En la prueba de integración FieldResourceInjectionTest , en la línea 7, la resolución de la dependencia por nombre se logra pasando el nombre del bean como un valor de atributo a la anotación @Resource :
@Resource(name="namedFile") private File defaultFile;
Esta configuración resolverá las dependencias utilizando la ruta de ejecución de coincidencia por nombre. El bean namedFile debe definirse en el contexto de aplicación ApplicationContextTestResourceNameType .
Tenga en cuenta que la identificación del bean y el valor del atributo de referencia correspondiente deben coincidir:
@Configuration public class ApplicationContextTestResourceNameType { @Bean(name="namedFile") public File namedFile() { File namedFile = new File("namedFile.txt"); return namedFile; } }
Si no se define el bean en el contexto de la aplicación, se generará una org.springframework.beans.factory.NoSuchBeanDefinitionException . Esto se puede demostrar cambiando el valor del atributo pasado a la anotación @Bean , en el contexto de la aplicación ApplicationContextTestResourceNameType ; o cambiar el valor del atributo pasado a la anotación @Resource , en la prueba de integración FieldResourceInjectionTest .
2.1.2. Coincidencia por tipo
Para demostrar la ruta de ejecución de coincidencia por tipo, simplemente elimine el valor del atributo en la línea 7 de la prueba de integración FieldResourceInjectionTest para que tenga el siguiente aspecto:
@Resource private File defaultFile;
y vuelva a ejecutar la prueba.
La prueba aún pasará porque si la anotación @Resource no recibe un nombre de bean como valor de atributo, Spring Framework continuará con el siguiente nivel de precedencia, coincidencia por tipo, para intentar resolver la dependencia.
2.1.3. Partido por clasificatorio
Para demostrar la ruta de ejecución de emparejamiento por calificador, el escenario de prueba de integración se modificará para que haya dos beans definidos en el contexto de la aplicación ApplicationContextTestResourceQualifier :
@Configuration public class ApplicationContextTestResourceQualifier { @Bean(name="defaultFile") public File defaultFile() { File defaultFile = new File("defaultFile.txt"); return defaultFile; } @Bean(name="namedFile") public File namedFile() { File namedFile = new File("namedFile.txt"); return namedFile; } }
La prueba de integración QualifierResourceInjectionTest se utilizará para demostrar la resolución de dependencia de emparejamiento por calificador. En este escenario, se debe inyectar una dependencia de frijol específica en cada variable de referencia:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration( loader=AnnotationConfigContextLoader.class, classes=ApplicationContextTestResourceQualifier.class) public class QualifierResourceInjectionIntegrationTest { @Resource private File dependency1; @Resource private File dependency2; @Test public void givenResourceAnnotation_WhenField_ThenDependency1Valid(){ assertNotNull(dependency1); assertEquals("defaultFile.txt", dependency1.getName()); } @Test public void givenResourceQualifier_WhenField_ThenDependency2Valid(){ assertNotNull(dependency2); assertEquals("namedFile.txt", dependency2.getName()); } }
Ejecute la prueba de integración y se lanzará una org.springframework.beans.factory.NoUniqueBeanDefinitionException . Esta excepción se produce porque el contexto de la aplicación ha encontrado dos definiciones de bean de tipo Archivo y no se sabe qué bean debe resolver la dependencia.
Para resolver este problema, consulte la línea 7 a la línea 10 de la prueba de integración QualifierResourceInjectionTest :
@Resource private File dependency1; @Resource private File dependency2;
y agregue las siguientes líneas de código:
@Qualifier("defaultFile") @Qualifier("namedFile")
para que el bloque de código tenga el siguiente aspecto:
@Resource @Qualifier("defaultFile") private File dependency1; @Resource @Qualifier("namedFile") private File dependency2;
Ejecute la prueba de integración nuevamente, esta vez debería pasar. El objetivo de esta prueba era demostrar que incluso si hay varios beans definidos en el contexto de una aplicación, la anotación @Qualifier despeja cualquier confusión al permitir que se inyecten dependencias específicas en una clase.
2.2. Inyección de Setter
Las rutas de ejecución que se toman al inyectar dependencias en un campo son aplicables a la inyección basada en establecedores.
2.2.1. Coincidir por nombre
La única diferencia es que la prueba de integración MethodResourceInjectionTest tiene un método de establecimiento:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration( loader=AnnotationConfigContextLoader.class, classes=ApplicationContextTestResourceNameType.class) public class MethodResourceInjectionIntegrationTest { private File defaultFile; @Resource(name="namedFile") protected void setDefaultFile(File defaultFile) { this.defaultFile = defaultFile; } @Test public void givenResourceAnnotation_WhenSetter_ThenDependencyValid(){ assertNotNull(defaultFile); assertEquals("namedFile.txt", defaultFile.getName()); } }
La resolución de dependencias mediante la inyección de establecedores se realiza anotando el método de establecimiento correspondiente de una variable de referencia. Pase el nombre de la dependencia del bean como un valor de atributo a la anotación @Resource :
private File defaultFile; @Resource(name="namedFile") protected void setDefaultFile(File defaultFile) { this.defaultFile = defaultFile; }
The namedFile bean dependency will be reused in this example. The bean name and the corresponding attribute value must match.
Run the integration test as-is and it will pass.
To see that the dependency was indeed resolved by the match-by-name execution path, change the attribute value passed to the @Resource annotation to a value of your choice and run the test again. This time, the test will fail with a NoSuchBeanDefinitionException.
2.2.2. Match by Type
To demonstrate setter-based, match-by-type execution, we will use the MethodByTypeResourceTest integration test:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration( loader=AnnotationConfigContextLoader.class, classes=ApplicationContextTestResourceNameType.class) public class MethodByTypeResourceIntegrationTest { private File defaultFile; @Resource protected void setDefaultFile(File defaultFile) { this.defaultFile = defaultFile; } @Test public void givenResourceAnnotation_WhenSetter_ThenValidDependency(){ assertNotNull(defaultFile); assertEquals("namedFile.txt", defaultFile.getName()); } }
Run this test as-is, and it will pass.
In order to verify that the File dependency was indeed resolved by the match-by-type execution path, change the class type of the defaultFile variable to another class type like String. Execute the MethodByTypeResourceTest integration test again and this time a NoSuchBeanDefinitionException will be thrown.
The exception verifies that match-by-type was indeed used to resolve the File dependency. The NoSuchBeanDefinitionException confirms that the reference variable name does not need to match the bean name. Instead, dependency resolution depends on the bean's class type matching the reference variable's class type.
2.2.3. Match by Qualifier
The MethodByQualifierResourceTest integration test will be used to demonstrate the match-by-qualifier execution path:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration( loader=AnnotationConfigContextLoader.class, classes=ApplicationContextTestResourceQualifier.class) public class MethodByQualifierResourceIntegrationTest { private File arbDependency; private File anotherArbDependency; @Test public void givenResourceQualifier_WhenSetter_ThenValidDependencies(){ assertNotNull(arbDependency); assertEquals("namedFile.txt", arbDependency.getName()); assertNotNull(anotherArbDependency); assertEquals("defaultFile.txt", anotherArbDependency.getName()); } @Resource @Qualifier("namedFile") public void setArbDependency(File arbDependency) { this.arbDependency = arbDependency; } @Resource @Qualifier("defaultFile") public void setAnotherArbDependency(File anotherArbDependency) { this.anotherArbDependency = anotherArbDependency; } }
The objective of this test is to demonstrate that even if multiple bean implementations of a particular type are defined in an application context, a @Qualifier annotation can be used together with the @Resource annotation to resolve a dependency.
Similar to field-based dependency injection, if there are multiple beans defined in an application context, a NoUniqueBeanDefinitionException is thrown if no @Qualifier annotation is used to specify which bean should be used to resolve dependencies.
3. The @Inject Annotation
The @Inject annotation belongs to the JSR-330 annotations collection. This annotation has the following execution paths, listed by precedence:
- Match by Type
- Match by Qualifier
- Match by Name
These execution paths are applicable to both setter and field injection. In order to access the @Inject annotation, the javax.inject library has to be declared as a Gradle or Maven dependency.
For Gradle:
testCompile group: 'javax.inject', name: 'javax.inject', version: '1'
For Maven:
javax.inject javax.inject 1
3.1. Field Injection
3.1.1. Match by Type
The integration test example will be modified to use another type of dependency, namely the ArbitraryDependency class. The ArbitraryDependency class dependency merely serves as a simple dependency and holds no further significance. It is listed as follows:
@Component public class ArbitraryDependency { private final String label = "Arbitrary Dependency"; public String toString() { return label; } }
The FieldInjectTest integration test in question is listed as follows:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration( loader=AnnotationConfigContextLoader.class, classes=ApplicationContextTestInjectType.class) public class FieldInjectIntegrationTest { @Inject private ArbitraryDependency fieldInjectDependency; @Test public void givenInjectAnnotation_WhenOnField_ThenValidDependency(){ assertNotNull(fieldInjectDependency); assertEquals("Arbitrary Dependency", fieldInjectDependency.toString()); } }
Unlike the @Resource annotation, which resolves dependencies by name first; the default behavior of the @Inject annotation resolves dependencies by type.
This means that even if a class reference variable name differs from the bean name, the dependency will still be resolved, provided that the bean is defined in the application context. Note how the reference variable name in the following test:
@Inject private ArbitraryDependency fieldInjectDependency;
differs from the bean name configured in the application context:
@Bean public ArbitraryDependency injectDependency() { ArbitraryDependency injectDependency = new ArbitraryDependency(); return injectDependency; }
and when the test is executed, it is able to resolve the dependency.
3.1.2. Match by Qualifier
But what if there are multiple implementations of a particular class type, and a certain class requires a specific bean? Let us modify the integration testing example so that another dependency is required.
In this example, we subclass the ArbitraryDependency class, used in the match-by-type example, to create the AnotherArbitraryDependency class:
public class AnotherArbitraryDependency extends ArbitraryDependency { private final String label = "Another Arbitrary Dependency"; public String toString() { return label; } }
The objective of each test case is to ensure that each dependency is injected correctly into each reference variable:
@Inject private ArbitraryDependency defaultDependency; @Inject private ArbitraryDependency namedDependency;
The FieldQualifierInjectTest integration test used to demonstrate match by qualifier is listed as follows:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration( loader=AnnotationConfigContextLoader.class, classes=ApplicationContextTestInjectQualifier.class) public class FieldQualifierInjectIntegrationTest { @Inject private ArbitraryDependency defaultDependency; @Inject private ArbitraryDependency namedDependency; @Test public void givenInjectQualifier_WhenOnField_ThenDefaultFileValid(){ assertNotNull(defaultDependency); assertEquals("Arbitrary Dependency", defaultDependency.toString()); } @Test public void givenInjectQualifier_WhenOnField_ThenNamedFileValid(){ assertNotNull(defaultDependency); assertEquals("Another Arbitrary Dependency", namedDependency.toString()); } }
If there are multiple implementations of a particular class in an application context and the FieldQualifierInjectTest integration test attempts to inject the dependencies in the manner listed below:
@Inject private ArbitraryDependency defaultDependency; @Inject private ArbitraryDependency namedDependency;
a NoUniqueBeanDefinitionException will be thrown.
Throwing this exception is the Spring Framework's way of pointing out that there are multiple implementations of a certain class and it is confused about which one to use. In order to elucidate the confusion, go to line 7 and 10 of the FieldQualifierInjectTest integration test:
@Inject private ArbitraryDependency defaultDependency; @Inject private ArbitraryDependency namedDependency;
pass the required bean name to the @Qualifier annotation, which is used together with the @Inject annotation. The code block will now look as follows:
@Inject @Qualifier("defaultFile") private ArbitraryDependency defaultDependency; @Inject @Qualifier("namedFile") private ArbitraryDependency namedDependency;
The @Qualifier annotation expects a strict match when receiving a bean name. Ensure that the bean name is passed to the Qualifier correctly, otherwise, a NoUniqueBeanDefinitionException will be thrown. Run the test again, and this time it should pass.
3.1.3. Match by Name
The FieldByNameInjectTest integration test used to demonstrate match by name is similar to the match by type execution path. The only difference is now a specific bean is required, as opposed to a specific type. In this example, we subclass the ArbitraryDependency class again to produce the YetAnotherArbitraryDependency class:
public class YetAnotherArbitraryDependency extends ArbitraryDependency { private final String label = "Yet Another Arbitrary Dependency"; public String toString() { return label; } }
In order to demonstrate the match-by-name execution path, we will use the following integration test:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration( loader=AnnotationConfigContextLoader.class, classes=ApplicationContextTestInjectName.class) public class FieldByNameInjectIntegrationTest { @Inject @Named("yetAnotherFieldInjectDependency") private ArbitraryDependency yetAnotherFieldInjectDependency; @Test public void givenInjectQualifier_WhenSetOnField_ThenDependencyValid(){ assertNotNull(yetAnotherFieldInjectDependency); assertEquals("Yet Another Arbitrary Dependency", yetAnotherFieldInjectDependency.toString()); } }
The application context is listed as follows:
@Configuration public class ApplicationContextTestInjectName { @Bean public ArbitraryDependency yetAnotherFieldInjectDependency() { ArbitraryDependency yetAnotherFieldInjectDependency = new YetAnotherArbitraryDependency(); return yetAnotherFieldInjectDependency; } }
Run the integration test as-is, and it will pass.
In order to verify that the dependency was indeed injected by the match-by-name execution path, change the value, yetAnotherFieldInjectDependency, that was passed in to the @Named annotation to another name of your choice. Run the test again – this time, a NoSuchBeanDefinitionException is thrown.
3.2. Setter Injection
Setter-based injection for the @Inject annotation is similar to the approach used for @Resource setter-based injection. Instead of annotating the reference variable, the corresponding setter method is annotated. The execution paths followed by field-based dependency injection also apply to setter based injection.
4. The @Autowired Annotation
The behaviour of @Autowired annotation is similar to the @Inject annotation. The only difference is that the @Autowired annotation is part of the Spring framework. This annotation has the same execution paths as the @Inject annotation, listed in order of precedence:
- Match by Type
- Match by Qualifier
- Match by Name
These execution paths are applicable to both setter and field injection.
4.1. Field Injection
4.1.1. Match by Type
The integration testing example used to demonstrate the @Autowired match-by-type execution path will be similar to the test used to demonstrate the @Inject match-by-type execution path. The FieldAutowiredTest integration test used to demonstrate match-by-type using the @Autowired annotation is listed as follows:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration( loader=AnnotationConfigContextLoader.class, classes=ApplicationContextTestAutowiredType.class) public class FieldAutowiredIntegrationTest { @Autowired private ArbitraryDependency fieldDependency; @Test public void givenAutowired_WhenSetOnField_ThenDependencyResolved() { assertNotNull(fieldDependency); assertEquals("Arbitrary Dependency", fieldDependency.toString()); } }
The application context for this integration test is listed as follows:
@Configuration public class ApplicationContextTestAutowiredType { @Bean public ArbitraryDependency autowiredFieldDependency() { ArbitraryDependency autowiredFieldDependency = new ArbitraryDependency(); return autowiredFieldDependency; } }
The objective of the integration test is to demonstrate that match-by-type takes first precedence over the other execution paths. Notice on line 8 of the FieldAutowiredTest integration test how the reference variable name:
@Autowired private ArbitraryDependency fieldDependency;
is different to the bean name in the application context:
@Bean public ArbitraryDependency autowiredFieldDependency() { ArbitraryDependency autowiredFieldDependency = new ArbitraryDependency(); return autowiredFieldDependency; }
When the test is run, it will pass.
In order to confirm that the dependency was indeed resolved using the match-by-type execution path, change the type of the fieldDependency reference variable and run the integration test again. This time round the FieldAutowiredTest integration test must fail, with a NoSuchBeanDefinitionException being thrown. This verifies that match-by-type was used to resolve the dependency.
4.1.2. Match by Qualifier
What if faced with a situation where multiple bean implementations have been defined in the application context, like the one listed below:
@Configuration public class ApplicationContextTestAutowiredQualifier { @Bean public ArbitraryDependency autowiredFieldDependency() { ArbitraryDependency autowiredFieldDependency = new ArbitraryDependency(); return autowiredFieldDependency; } @Bean public ArbitraryDependency anotherAutowiredFieldDependency() { ArbitraryDependency anotherAutowiredFieldDependency = new AnotherArbitraryDependency(); return anotherAutowiredFieldDependency; } }
If the FieldQualifierAutowiredTest integration test, listed below, is executed:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration( loader=AnnotationConfigContextLoader.class, classes=ApplicationContextTestAutowiredQualifier.class) public class FieldQualifierAutowiredIntegrationTest { @Autowired private ArbitraryDependency fieldDependency1; @Autowired private ArbitraryDependency fieldDependency2; @Test public void givenAutowiredQualifier_WhenOnField_ThenDep1Valid(){ assertNotNull(fieldDependency1); assertEquals("Arbitrary Dependency", fieldDependency1.toString()); } @Test public void givenAutowiredQualifier_WhenOnField_ThenDep2Valid(){ assertNotNull(fieldDependency2); assertEquals("Another Arbitrary Dependency", fieldDependency2.toString()); } }
a NoUniqueBeanDefinitionException will be thrown.
The exception is due to the ambiguity caused by the two beans defined in the application context. The Spring Framework does not know which bean dependency should be autowired to which reference variable. Resolve this issue by adding the @Qualifier annotation to lines 7 and 10 of the FieldQualifierAutowiredTest integration test:
@Autowired private FieldDependency fieldDependency1; @Autowired private FieldDependency fieldDependency2;
so that the code block looks as follows:
@Autowired @Qualifier("autowiredFieldDependency") private FieldDependency fieldDependency1; @Autowired @Qualifier("anotherAutowiredFieldDependency") private FieldDependency fieldDependency2;
Run the test again, and this time it will pass.
4.1.3. Match by Name
The same integration test scenario will be used to demonstrate the match-by-name execution path when using the @Autowired annotation to inject a field dependency. When autowiring dependencies by name, the @ComponentScan annotation must be used with the application context, ApplicationContextTestAutowiredName:
@Configuration @ComponentScan(basePackages={"com.baeldung.dependency"}) public class ApplicationContextTestAutowiredName { }
The @ComponentScan annotation will search packages for Java classes that have been annotated with the @Component annotation. For example, in the application context, the com.baeldung.dependency package will be scanned for classes that have been annotated with the @Component annotation. In this scenario, the Spring Framework must detect the ArbitraryDependency class, which has the @Component annotation:
@Component(value="autowiredFieldDependency") public class ArbitraryDependency { private final String label = "Arbitrary Dependency"; public String toString() { return label; } }
The attribute value, autowiredFieldDependency, passed into the @Component annotation, tells the Spring Framework that the ArbitraryDependency class is a component named autowiredFieldDependency. In order for the @Autowired annotation to resolve dependencies by name, the component name must correspond with the field name defined in the FieldAutowiredNameTest integration test; please refer to line 8:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration( loader=AnnotationConfigContextLoader.class, classes=ApplicationContextTestAutowiredName.class) public class FieldAutowiredNameIntegrationTest { @Autowired private ArbitraryDependency autowiredFieldDependency; @Test public void givenAutowiredAnnotation_WhenOnField_ThenDepValid(){ assertNotNull(autowiredFieldDependency); assertEquals("Arbitrary Dependency", autowiredFieldDependency.toString()); } }
When the FieldAutowiredNameTest integration test is run as-is, it will pass.
But how do we know that the @Autowired annotation really did invoke the match-by-name execution path? Change the name of the reference variable autowiredFieldDependency to another name of your choice, then run the test again.
This time, the test will fail and a NoUniqueBeanDefinitionException is thrown. A similar check would be to change the @Component attribute value, autowiredFieldDependency, to another value of your choice and run the test again. A NoUniqueBeanDefinitionException will also be thrown.
This exception is proof that if an incorrect bean name is used, no valid bean will be found. Therefore, the match-by-name execution path was invoked.
4.2. Setter Injection
Setter-based injection for the @Autowired annotation is similar the approach demonstrated for @Resource setter-based injection. Instead of annotating the reference variable with the @Inject annotation, the corresponding setter is annotated. The execution paths followed by field-based dependency injection also apply to setter-based injection.
5. Applying These Annotations
This raises the question, which annotation should be used and under what circumstances? The answer to these questions depends on the design scenario faced by the application in question, and how the developer wishes to leverage polymorphism based on the default execution paths of each annotation.
5.1. Application-Wide Use of Singletons Through Polymorphism
If the design is such that application behaviors are based on implementations of an interface or an abstract class, and these behaviors are used throughout the application, then use either the @Inject or @Autowired annotation.
The benefit of this approach is that when the application is upgraded, or a patch needs to be applied in order to fix a bug; then classes can be swapped out with minimal negative impact to the overall application behavior. In this scenario, the primary default execution path is match-by-type.
5.2. Fine-Grained Application Behavior Configuration Through Polymorphism
If the design is such that the application has complex behavior, each behavior is based on different interfaces/abstract classes, and usage of each of these implementations varies across the application, then use the @Resource annotation. In this scenario, the primary default execution path is match-by-name.
5.3. Dependency Injection Should Be Handled Solely by the Jakarta EE Platform
If there is a design mandate for all dependencies to be injected by the Jakarta EE Platform and not Spring, then the choice is between the @Resource annotation and the @Inject annotation. You should narrow down the final decision between the two annotations, based on which default execution path is required.
5.4. Dependency Injection Should Be Handled Solely by the Spring Framework
Si el mandato es que todas las dependencias sean manejadas por Spring Framework, la única opción es la anotación @Autowired .
5.5. Resumen de la discusión
La siguiente tabla resume la discusión.
Guión | @Recurso | @Inyectar | @Autowired |
---|---|---|---|
Uso de singleton en toda la aplicación mediante polimorfismo | ✗ | ✔ | ✔ |
Configuración detallada del comportamiento de la aplicación mediante polimorfismo | ✔ | ✗ | ✗ |
La inyección de dependencia debe ser manejada únicamente por la plataforma Jakarta EE. | ✔ | ✔ | ✗ |
La inyección de dependencia debe ser manejada únicamente por Spring Framework | ✗ | ✗ | ✔ |
6. Conclusión
El artículo tenía como objetivo proporcionar una visión más profunda del comportamiento de cada anotación. Comprender cómo se comporta cada anotación contribuirá a un mejor diseño y mantenimiento general de la aplicación.
El código utilizado durante la discusión se puede encontrar en GitHub.