This annotation does bean injection, like the @Autowired
and @Inject
annotations.
This annotation is packaged with Jakarta EE and will work on your Spring projects.
You can use this annotation almost in the same way you use the other annotations used to inject dependencies.
Using in-field injection and set methods is possible, but constructors are not supported.
It can match the type and the bean name definition. Also, you can combine it with the @Qualifier annotation.
It can simplify migrating projects between Jakarta and Spring.
Let’s take a look at some examples of how to use it.
Field Injection with @resource
This is the standard way, using above the field that will be injected.
@Repository
public class MyRepository {
}
@Component
public class MyService {
@Resource
private MyRepository myRepository;
}
Setter Injection
Another alternative to injecting beans with @Resource
is to use the setter method.
@Repository
public class MySetterRepository {
}
@Component
public class MySetterService {
private static final Logger log = LoggerFactory.getLogger(MySetterService.class);
private MySetterRepository mySetterRepository;
@Resource
public void setMySetterRepository(MySetterRepository mySetterRepository) {
this.mySetterRepository = mySetterRepository;
}
}
Combining with @Qualifier
You can use the @Resource
annotation combined with the @Qualifier
in the same way you would do when using the @Autowired
.
@Repository("anotherRepository")
public class AnotherRepository {
}
@Repository("specificRepository")
public class SpecificRepository {
}
@Component
public class MyQualifierService {
@Resource
@Qualifier("specificRepository")
private SpecificRepository specificRepository;
public void performService() {
specificRepository.doSomething();
}
}
Matching by Name: The 'name' Attribute
If you do not want to use the @Qualifier
annotation, you can use the name
attribute from the @Resource
annotation, to define the bean which will be injected.
@Repository("anotherRepository")
public class AnotherRepository {
}
@Repository("specificRepository")
public class SpecificRepository {
}
@Component
public class MyNameService {
@Resource(name = "specificRepository")
private SpecificRepository specificNameRepository;
}
Conclusion
In this blog post, you learned about the @Resouce
an alternative to the @Autowired
annotation to inject beans, that can work both with Jakarta and Spring.
If you like this topic, make sure to follow me. In the following days, I’ll be explaining more about Spring annotations! Stay tuned!
Follow me!
Top comments (0)