

Spring @Resource Annotation Example

JDK JSR-250 provides a property or method-level annotation that supports the Autowiring functionality in the spring framework. Spring supports this injection by using the @Resource annotation, applied to either the property or the setter method of a bean. This tutorial will explore the JDK-specific @Resource annotation in the spring.
1. Introduction
1.1 spring framework.
- Spring is an open-source framework created to address the complexity of an enterprise application development
- One of the chief advantages of the Spring framework is its layered architecture, which allows the developer to be selective about which of its components they can use while providing a cohesive framework for J2EE application development
- Support for Transaction Management
- Support for interaction with the different databases
- Integration with the Object Relationship frameworks for e.g. Hibernate, iBatis etc
- Support for Dependency Injection which means all the required dependencies will be resolved with the help of containers
- Support for REST style web-services

We will contact you soon.
1.2 @Resource annotation in spring
The @Resource annotation in spring performs the autowiring functionality. This annotation follows the autowire=byName semantics in the XML based configuration i.e. it takes the name attribute for the injection. Below snippet shows how to use this annotation.
Code Snippet
This annotation takes an optional name argument. In case no name attribute is specified with this annotation, the default name is interpreted from the field-name or the setter method (i.e. the bean property name). Always remember that if the @Resource annotation doesn’t find the bean with the name it will automatically switch it’s autowiring technique to autowire=byType (i.e. @Autowired annotation).
1.2.1 Activate @Resource annotation
To activate this annotation in spring, developers will have to include the <context:annotation-config /> tag in the configuration file. Below snippet shows how to include this tag in the configuration file:
2. Spring @Resource Annotation Example
2.1 tools used, 2.2 project structure.

2.3 Project Creation

3. Application Building
3.1 maven dependencies, 3.2 java class creation, 3.2.1 implementation of company model, 3.2.2 implementation of employee model, 3.2.3 implementation of utility class, 3.3 configuration files, 3.3.1 resource, 4. run the application.

5. Project Demo
6. conclusion, 7. download the eclipse project, want to know how to develop your skillset to become a java rockstar.

Related Articles

Tomcat vs. Jetty vs. Undertow: Comparison of Spring Boot Embedded Servlet Containers
Load environment configurations and properties with spring example, using mockrestserviceserver to test a rest client, spring batch jobrepository example, spring framework jmstemplate example, 20 spring framework best practices, spring batch scheduler example, spring batch tasklet example.

This site uses Akismet to reduce spam. Learn how your comment data is processed .
- ALL TUTORIALS
- SPRING BOOT
@Resource Annotation in Spring
@resource vs @autowired, @resource at field level, @resource at method level, @resource by type, download source code.

- @ContextConfiguration Example in Spring Test
- @SpyBean Example in Spring Test
- Spring RestTemplate.exchange()
- @TestPropertySource Example in Spring Test
- Spring RestTemplate.getForObject()
- @ActiveProfiles Example in Spring Test
- Spring RestTemplate.postForEntity()
- Spring Component Scan Include and Exclude Filter Example
- Spring Data MongoRepository Update
- Spring RestTemplate.getForEntity()
- Spring RestTemplate.postForObject()
- Spring JdbcTemplate.queryForList()
- @PreAuthorize and @PostAuthorize in Spring Security
- Spring Batch + H2 Database Example
- Spring @JmsListener Example
- Spring @Value Default Value
- Spring Data MongoTemplate Example
- Spring Boot SOAP Web Service Example
- Spring Boot REST Example
- Spring Boot CrudRepository Example
Mobile Apps

©2023 concretepage.com | Privacy Policy | Contact Us
- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Meaning of @Resource annotation
I'm unable to understand the meaning of the @Resource annotation. I've looked at online resources, but they seem to explain the same in a way which is difficult to comprehend. Can someone please explain the meaning of @Resource in a simplistic manner, if possible?
- annotations

- @Resource means get me a known resource by name. The name is extracted from the name of the annotated field or it's taken from the name parameter. Refer this link : stackoverflow.com/questions/4093504/resource-vs-autowired – Ashraf.Shk786 May 18, 2018 at 21:25
- Possible duplicate of @Resource vs @Autowired – Ashraf.Shk786 May 18, 2018 at 21:25
2 Answers 2
First of all, to understand the point of @Resource you need to understand the Inversion of Control (IoC) .
Inversion of Control is a principle in software development which goes that the control of objects should be transferred to a container or a framework.
Dependency Injection (DI) is a pattern of IoC implementation, where the control being inverted is the setting of object’s dependencies. The act of composing objects with other objects (injecting) is done by a container rather than by the objects themselves.
Using a DI framework (like Spring IoC or EJB ) you're creating your POJOs and configuring the framework (a POJO configured such way called a Bean ). A Bean may have different scopes, like singleton (1 object instance per container), prototype (creates a new instance of an object per injection or explicit call) and etc.

So far, so good. What's next? It's time to use our beans .
@Resource is the annotation that will help to extract beans from the container.
There are several lookup options to extract beans:
- Match by Name
- Match by Type
- Match by Qualifier
Using @Resource without any parameters will trigger Match by Type lookup type.
There is an example of usage or @Resource with field injection and Spring framework with Java-based configuration and Match by Name :
@Resource is usually used to inject data sources, singleton services, context configurations and etc.
- Awesome explanation, I really like it. – Stefan Sonnenberg-Carstens May 6, 2020 at 6:53
- 5 According to the Spring docs ( docs.spring.io/spring-framework/docs/current/… ) @Resource without any parameters will trigger Match by Name: "If no name is explicitly specified, the default name is derived from the field name" – xtian Oct 9, 2020 at 9:00
The @Resource annotation is used to identify a class, field, or method that upon initialization, the resource will be injected. For a class-based @Resource, the "resource is looked up by the application at runtime".
Further information can be found here: https://docs.oracle.com/javaee/6/tutorial/doc/bncjk.html

Your Answer
Sign up or log in, post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged java annotations or ask your own question .
- The Overflow Blog
- Five Stack Exchange sites turned ten years old this quarter!
- “Move fast and break things” doesn’t apply to other people’s savings (Ep. 544)
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- Launching the CI/CD and R Collectives and community editing features for...
- The [amazon] tag is being burninated
- Temporary policy: ChatGPT is banned
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
Hot Network Questions
- Does oven polenta actually work?
- Is it inappropriate to tell my boss that "baby talk" is unprofessional?
- What laws would Jesus be breaking if he were to turn water into wine today?
- Why does Jesus change the speech from who is the greatest to who is the first?
- Scales name convention
- What is the purpose of enclosing all return values and arguments of a method in separate classes?
- How to write enum in smartPy?
- What is the name of the color used by the SBB (Swiss Federal Railway) in the 1920s to paint their locomotive?
- Google maps for Space exploration
- Each Element of Obarray is A Bucket?
- Why did Ukraine abstain from the UNHRC vote on China?
- Max-heap implementation in C
- Temperature Pressure Release (TPR) Valve Leaking
- How to migrate from Kusama to Polkadot?
- What do we really know about lotteries?
- Options for "Cancel this operation?" are "Cancel" and "Yes"; what would be better wording for customers in a hurry?
- In a large list, should the filter and search be combined or separated?
- Why did Chandrasekhar use 2.5 for molecular weight in 1931?
- Should the sticker on top of a HDD be peeled?
- 21 hr layover in ORY airport. Bad idea?
- How can I run conduit to boxes in the ceiling and keep the covers accessible?
- Should I ask why they are interested in me in an interview for a faculty position?
- Is this a viable theoretical method of fast interplanetary space travel?
- Mando's Mandatory Meandering?
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .
- Send Message
- Core Java Tutorials
- Java EE Tutorials
- Java Swing Tutorials
- Spring Framework Tutorials
- Unit Testing
- Build Tools
- Misc Tutorials
- OrderServiceClient.java
- OrderServiceImpl1.java
- OrderServiceImpl2.java
- OrderService.java
- AppRunner.java
- Source Allies
- 4501 NW Urbandale Dr. Urbandale, IA 50322
- (515) 279-2640
〈 Back to Blog
Spring injection with @resource, @autowired and @inject.
I’ve been asked several times to explain the difference between injecting Spring beans with ‘@Resource’, ‘@Autowired’, and ‘@Inject’. While I received a few opinions from colleagues and read a couple of posts on this topic I didn’t feel like I had a complete picture.
Annotations
In order to explore the behavior of each annotation I fired up Spring Tool Suite and started debugging the code. I used Spring 3.0.5.RELEASE in my research. The following is a summary of my findings.
I wanted to know how ‘@Resource’, ‘@Autowired’, and ‘@Inject’ resolved dependencies. I created an interface called ‘Party’ and created two implementations classes. This allowed me to inject beans without using the concrete type. This provided the flexibility I needed to determine how Spring resolves beans when there are multiple type matches.
‘Person’ is a component and it implements ‘Party’.
‘Organization’ is a component and it implements ‘Party’.
I setup a Spring context that scans both of these packages for beans marked with ‘@Component’.
Test 1: Ambiguous Beans In this test I injected a ‘Party’ bean that has multiple implementations in the Spring context.
In all three cases a ‘NoSuchBeanDefinitionException’ is thrown. While this exception’s name implies that no beans were found, the message explains that two beans were found. All of these annotations result in the same exception.
Test 2: Field Name In this test I named the Party field person. By default beans marked with ‘@Component’ will have the same name as the class. Therefore the name of the class ‘Person’ is person.
‘@Resource’ can also take an optional ‘name’ attribute. This is equivalent to the ‘@Resource’ code above. In this case the field variable name remains ‘party’. There is no equivalent syntax for ‘@Autowired’ or ‘@Inject’. Instead you would have to use a ‘@Qualifier’. This syntax will be covered later.
All four of these styles inject the ‘Person’ bean. <
Test 3: Field Type In this test I changed the type to be a ‘Person’.
All of these annotations inject the ‘Person’ bean.
Test 4: Default Name Qualifier In this test I use a ‘@Qualifier’ annotation to point to the default name of the ‘Person’ component.
Test 5: Qualified Name I added a ‘@Qualifier’ annotation to the ‘Person’ class
In this test I use a ‘@Qualifier’ annotation to point to the qualified name of the ‘Person’ component.
Test 6: List of Beans In this test I inject a list of beans.
All of these annotations inject 2 beans into the list. This can also be accomplished with a ‘@Qualifier’. Each bean marked with a specific qualifier will be added to the list.
Test 7: Conflicting messages In this test I add a bad ‘@Qualifier’ and a matching field name.
In this case the field marked with ‘@Resource’ uses the field name and ignores the ‘@Qualifier’. As a result the ‘Person’ bean is injected.
However the ‘@Autowired’ and ‘@Inject’ field throw a ‘NoSuchBeanDefinitionException’ error because it can not find a bean that matches the ‘@Qualifier’.
Conclusions
With the exception of test 2 & 7 the configuration and outcomes were identical. When I looked under the hood I determined that the ‘@Autowired’ and ‘@Inject’ annotation behave identically. Both of these annotations use the ‘AutowiredAnnotationBeanPostProcessor’ to inject dependencies. ‘@Autowired’ and ‘@Inject’ can be used interchangeable to inject Spring beans. However the ‘@Resource’ annotation uses the ‘CommonAnnotationBeanPostProcessor’ to inject dependencies. Even though they use different post processor classes they all behave nearly identically. Below is a summary of their execution paths.
@Autowired and @Inject
- Matches by Type
- Restricts by Qualifiers
- Matches by Name
- Restricts by Qualifiers (ignored if match is found by name)
While it could be argued that ‘@Resource’ will perform faster by name than ‘@Autowired’ and ‘@Inject’ it would be negligible. This isn’t a sufficient reason to favor one syntax over the others. I do however favor the ‘@Resource’ annotation for it’s concise notation style.
You may argue that they can be equal concise if you use the field name to identify the bean name.
True enough, but what happens if you want to refactor your code? By simply renaming the field name you’re no longer referring to the same bean. I recommend the following practices when wiring beans with annotations.
Spring Annotation Style Best Practices
- Explicitly name your component [@Component("beanName")]
- Use '@Resource' with the 'name' attribute [@Resource(name="beanName")]
- Avoid '@Qualifier' annotations unless you want to create a list of similar beans. For example you may want to mark a set of rules with a specific '@Qualifier' annotation. This approach makes it simple to inject a group of rule classes into a list that can be used for processing data.
- Scan specific packages for components [context:component-scan base-package="com.sourceallies.person"]. While this will result in more component-scan configurations it reduces the chance that you'll add unnecessary components to your Spring context.
Following these guidelines will increase the readability and stability of your Spring annotation configurations.
Related Links
Testing Spring Wiring Beanoh Spring Wiring Test Framework
Recent Posts

Why Your SMART Goals Aren't Working: The Key to More Successful Projects

Material Market: Coordinating Distributed Events

Reference Data Without the Database

Getting Started with ML Part 3: Using AutoML
Tech Tutorials
Monday, january 2, 2023, @resource annotation in spring autowiring.
Apart from supporting JSR-330 annotations like @Inject and @Named for autowiring, Spring also supports injection using the JSR-250 @Resource annotation on fields or bean property setter methods .
Spring @Resource annotation
For example, if we take the following class then bean with name " payment " will be injected into its setter method
@Autowired and @Inject annotations
@resource annotation in spring if(typeof ez_ad_units='undefined'){ez_ad_units.push([[300,250],'netjstech_com-large-mobile-banner-2','ezslot_13',122,'0','0'])};__ez_fad_position('div-gpt-ad-netjstech_com-large-mobile-banner-2-0');.
So you can see in case of @Autowired and @Inject switch to "byType" happens only after restricting by Qualifier. Whereas with @Resource it switches to byType if it doesn't find the bean by name.

Spring @Resource annotation example
Here we have a class PayServiceImpl which has a field payment of type IPayment which we have to autowire. Also class CashPayment which implements IPayment interface .
PayServiceImpl class
Interface IPayment
XML configuration file
Switching to byType using @Resource annotation
As already mentioned @Resource annotation will switch to "byType" if it is not able to match the bean by name. You can test it by removing the "name" attribute from @Resource annotation.
BeanNotOfRequiredTypeException when using @Resource annotation
IPayCash interface
If you see here in XML configuration CashPayment bean is defined with id " cashPaymentBean " and in Class PayServiceImpl @Resource annotation also has the same name attribute @Resource(name="cashPaymentBean") so name matching will happen without any problem.
You may also like-
If you need postmortem of any topic then please come here and feel the open operation of any topic and by the end you will be left with confidence over that particular topic.
3.9 Annotation-based container configuration
As mentioned in Section 3.8.1.2, “Example: The RequiredAnnotationBeanPostProcessor” , using a BeanPostProcessor in conjunction with annotations is a common means of extending the Spring IoC container. For example, Spring 2.0 introduced the possibility of enforcing required properties with the @Required annotation. As of Spring 2.5, it is now possible to follow that same general approach to drive Spring's dependency injection. Essentially, the @Autowired annotation provides the same capabilities as described in Section 3.4.5, “Autowiring collaborators” but with more fine-grained control and wider applicability. Spring 2.5 also adds support for JSR-250 annotations such as @Resource , @PostConstruct , and @PreDestroy . Use of these annotations also requires that certain BeanPostProcessors be registered within the Spring container. As always, you can register them as individual bean definitions, but they can also be implicitly registered by including the following tag in an XML-based Spring configuration (notice the inclusion of the context namespace):
(The implicitly registered post-processors include AutowiredAnnotationBeanPostProcessor , CommonAnnotationBeanPostProcessor , PersistenceAnnotationBeanPostProcessor , as well as the aforementioned RequiredAnnotationBeanPostProcessor .)
3.9.1 @Required
The @Required annotation applies to bean property setter methods, as in the following example:
This annotation simply indicates that the affected bean property must be populated at configuration time, through an explicit property value in a bean definition or through autowiring. The container throws an exception if the affected bean property has not been populated; this allows for eager and explicit failure, avoiding NullPointerException s or the like later on. It is still recommended that you put assertions into the bean class itself, for example, into an init method. Doing so enforces those required references and values even when you use the class outside of a container.
3.9.2 @Autowired
As expected, you can apply the @Autowired annotation to "traditional" setter methods:
You can also apply the annotation to methods with arbitrary names and/or multiple arguments:
You can apply @Autowired to constructors and fields:
It is also possible to provide all beans of a particular type from the ApplicationContext by adding the annotation to a field or method that expects an array of that type:
The same applies for typed collections:
Even typed Maps can be autowired as long as the expected key type is String . The Map values will contain all beans of the expected type, and the keys will contain the corresponding bean names:
By default, the autowiring fails whenever zero candidate beans are available; the default behavior is to treat annotated methods, constructors, and fields as indicating required dependencies. This behavior can be changed as demonstrated below.
You can also use @Autowired for interfaces that are well-known resolvable dependencies: BeanFactory , ApplicationContext , ResourceLoader , ApplicationEventPublisher , and MessageSource . These interfaces and their extended interfaces, such as ConfigurableApplicationContext or ResourcePatternResolver , are automatically resolved, with no special setup necessary.
3.9.3 Fine-tuning annotation-based autowiring with qualifiers
Because autowiring by type may lead to multiple candidates, it is often necessary to have more control over the selection process. One way to accomplish this is with Spring's @Qualifier annotation. You can associate qualifier values with specific arguments, narrowing the set of type matches so that a specific bean is chosen for each argument. In the simplest case, this can be a plain descriptive value:
The @Qualifier annotation can also be specified on individual constructor arguments or method parameters:
The corresponding bean definitions appear as follows. The bean with qualifier value "main" is wired with the constructor argument that is qualified with the same value.
For a fallback match, the bean name is considered a default qualifier value. Thus you can define the bean with an id "main" instead of the nested qualifier element, leading to the same matching result. However, although you can use this convention to refer to specific beans by name, @Autowired is fundamentally about type-driven injection with optional semantic qualifiers. This means that qualifier values, even with the bean name fallback, always have narrowing semantics within the set of type matches; they do not semantically express a reference to a unique bean id. Good qualifier values are "main" or "EMEA" or "persistent", expressing characteristics of a specific component that are independent from the bean id, which may be auto-generated in case of an anonymous bean definition like the one in the preceding example.
Qualifiers also apply to typed collections, as discussed above, for example, to Set<MovieCatalog> . In this case, all matching beans according to the declared qualifiers are injected as a collection. This implies that qualifiers do not have to be unique; they rather simply constitute filtering criteria. For example, you can define multiple MovieCatalog beans with the same qualifier value "action"; all of which would be injected into a Set<MovieCatalog> annotated with @Qualifier("action") .
You can create your own custom qualifier annotations. Simply define an annotation and provide the @Qualifier annotation within your definition:
Then you can provide the custom qualifier on autowired fields and parameters:
Next, provide the information for the candidate bean definitions. You can add <qualifier/> tags as sub-elements of the <bean/> tag and then specify the type and value to match your custom qualifier annotations. The type is matched against the fully-qualified class name of the annotation. Or, as a convenience if no risk of conflicting names exists, you can use the short class name. Both approaches are demonstrated in the following example.
In Section 3.10, “Classpath scanning and managed components” , you will see an annotation-based alternative to providing the qualifier metadata in XML. Specifically, see Section 3.10.7, “Providing qualifier metadata with annotations” .
In some cases, it may be sufficient to use an annotation without a value. This may be useful when the annotation serves a more generic purpose and can be applied across several different types of dependencies. For example, you may provide an offline catalog that would be searched when no Internet connection is available. First define the simple annotation:
Then add the annotation to the field or property to be autowired:
Now the bean definition only needs a qualifier type :
You can also define custom qualifier annotations that accept named attributes in addition to or instead of the simple value attribute. If multiple attribute values are then specified on a field or parameter to be autowired, a bean definition must match all such attribute values to be considered an autowire candidate. As an example, consider the following annotation definition:
In this case Format is an enum:
The fields to be autowired are annotated with the custom qualifier and include values for both attributes: genre and format .
Finally, the bean definitions should contain matching qualifier values. This example also demonstrates that bean meta attributes may be used instead of the <qualifier/> sub-elements. If available, the <qualifier/> and its attributes take precedence, but the autowiring mechanism falls back on the values provided within the <meta/> tags if no such qualifier is present, as in the last two bean definitions in the following example.
3.9.4 CustomAutowireConfigurer
The CustomAutowireConfigurer is a BeanFactoryPostProcessor that enables you to register your own custom qualifier annotation types even if they are not annotated with Spring's @Qualifier annotation.
The particular implementation of AutowireCandidateResolver that is activated for the application context depends on the Java version. In versions earlier than Java 5, the qualifier annotations are not supported, and therefore autowire candidates are solely determined by the autowire-candidate value of each bean definition as well as by any default-autowire-candidates pattern(s) available on the <beans/> element. In Java 5 or later, the presence of @Qualifier annotations and any custom annotations registered with the CustomAutowireConfigurer will also play a role.
Regardless of the Java version, when multiple beans qualify as autowire candidates, the determination of a "primary" candidate is the same: if exactly one bean definition among the candidates has a primary attribute set to true , it will be selected.
3.9.5 @Resource
Spring also supports injection using the JSR-250 @Resource annotation on fields or bean property setter methods. This is a common pattern in Java EE 5 and Java 6, for example, in JSF 1.2 managed beans or JAX-WS 2.0 endpoints. Spring supports this pattern for Spring-managed objects as well.
@Resource takes a name attribute, and by default Spring interprets that value as the bean name to be injected. In other words, it follows by-name semantics, as demonstrated in this example:
If no name is specified explicitly, the default name is derived from the field name or setter method. In case of a field, it takes the field name; in case of a setter method, it takes the bean property name. So the following example is going to have the bean with name "movieFinder" injected into its setter method:
In the exclusive case of @Resource usage with no explicit name specified, and similar to @Autowired , @Resource finds a primary type match instead of a specific named bean and resolves well-known resolvable dependencies: the BeanFactory , ApplicationContext, ResourceLoader, ApplicationEventPublisher , and MessageSource interfaces.
Thus in the following example, the customerPreferenceDao field first looks for a bean named customerPreferenceDao, then falls back to a primary type match for the type CustomerPreferenceDao . The "context" field is injected based on the known resolvable dependency type ApplicationContext .
3.9.6 @PostConstruct and @PreDestroy
The CommonAnnotationBeanPostProcessor not only recognizes the @Resource annotation but also the JSR-250 lifecycle annotations. Introduced in Spring 2.5, the support for these annotations offers yet another alternative to those described in the sections on initialization callbacks and destruction callbacks . Provided that the CommonAnnotationBeanPostProcessor is registered within the Spring ApplicationContext , a method carrying one of these annotations is invoked at the same point in the lifecycle as the corresponding Spring lifecycle interface method or explicitly declared callback method. In the example below, the cache will be pre-populated upon initialization and cleared upon destruction.
Resource Injection
The javax.annotation.Resource annotation is used to declare a reference to a resource; @Resource can decorate a class, a field, or a method. The container will inject the resource referred to by @Resource into the component either at runtime or when the component is initialized, depending on whether field/method injection or class injection is used. With field-based and method-based injection, the container will inject the resource when the application is initialized. For class-based injection, the resource is looked up by the application at runtime.
The @Resource annotation has the following elements:
name : The JNDI name of the resource
type : The Java language type of the resource
authenticationType : The authentication type to use for the resource
shareable : Indicates whether the resource can be shared
mappedName : A nonportable, implementation-specific name to which the resource should be mapped
description : The description of the resource
The name element is the JNDI name of the resource and is optional for field-based and method-based injection. For field-based injection, the default name is the field name qualified by the class name. For method-based injection, the default name is the JavaBeans property name, based on the method qualified by the class name. The name element must be specified for class-based injection.
The type of resource is determined by one of the following:
The type of the field the @Resource annotation is decorating for field-based injection
The type of the JavaBeans property the @Resource annotation is decorating for method-based injection
The type element of @Resource
For class-based injection, the type element is required.
The authenticationType element is used only for connection factory resources, such as the resources of a connector, also called the resource adapter, or data source. This element can be set to one of the javax.annotation.Resource.AuthenticationType enumerated type values: CONTAINER , the default, and APPLICATION .
The shareable element is used only for Object Resource Broker (ORB) instance resources or connection factory resource. This element indicates whether the resource can be shared between this component and other components and may be set to true , the default, or false .
The mappedName element is a nonportable, implementation-specific name to which the resource should be mapped. Because the name element, when specified or defaulted, is local only to the application, many Java EE servers provide a way of referring to resources across the application server. This is done by setting the mappedName element. Use of the mappedName element is nonportable across Java EE server implementations.
The description element is the description of the resource, typically in the default language of the system on which the application is deployed. This element is used to help identify resources and to help application developers choose the correct resource.
Field-Based Injection
To use field-based resource injection, declare a field and decorate it with the @Resource annotation. The container will infer the name and type of the resource if the name and type elements are not specified. If you do specify the type element, it must match the field’s type declaration.
In the following code, the container infers the name of the resource, based on the class name and the field name: com.example.SomeClass/myDB . The inferred type is javax.sql.DataSource.class :
In the following code, the JNDI name is customerDB , and the inferred type is javax.sql.DataSource.class :
Method-Based Injection
To use method-based injection, declare a setter method and decorate it with the @Resource annotation. The container will infer the name and type of the resource if the name and type elements are not specified. The setter method must follow the JavaBeans conventions for property names: The method name must begin with set , have a void return type, and only one parameter. If you do specify the type element, it must match the field’s type declaration.
In the following code, the container infers the name of the resource based on the class name and the field name: com.example.SomeClass/myDB . The inferred type is javax.sql.DataSource.class :
Class-Based Injection
To use class-based injection, decorate the class with a @Resource annotation, and set the required name and type elements:
The @Resources annotation is used to group together multiple @Resource declarations for class-based injection. The following code shows the @Resources annotation containing two @Resource declarations. One is a Java Message Service message queue, and the other is a JavaMail session:
Copyright © 2013, Oracle and/or its affiliates. All rights reserved. Legal Notices
Scripting on this page tracks web page traffic, but does not change the content in any way.
- Data Structure & Algorithm Classes (Live)
- System Design (Live)
- DevOps(Live)
- Explore More Live Courses
- Interview Preparation Course
- Data Science (Live)
- GATE CS & IT 2024
- Data Structure & Algorithm-Self Paced(C++/JAVA)
- Data Structures & Algorithms in Python
- Explore More Self-Paced Courses
- C++ Programming - Beginner to Advanced
- Java Programming - Beginner to Advanced
- C Programming - Beginner to Advanced
- Full Stack Development with React & Node JS(Live)
- Java Backend Development(Live)
- Android App Development with Kotlin(Live)
- Python Backend Development with Django(Live)
- Complete Data Science Program(Live)
- Mastering Data Analytics
- DevOps Engineering - Planning to Production
- CBSE Class 12 Computer Science
- School Guide
- All Courses
- Linked List
- Binary Tree
- Binary Search Tree
- Advanced Data Structure
- All Data Structures
- Asymptotic Analysis
- Worst, Average and Best Cases
- Asymptotic Notations
- Little o and little omega notations
- Lower and Upper Bound Theory
- Analysis of Loops
- Solving Recurrences
- Amortized Analysis
- What does 'Space Complexity' mean ?
- Pseudo-polynomial Algorithms
- Polynomial Time Approximation Scheme
- A Time Complexity Question
- Searching Algorithms
- Sorting Algorithms
- Graph Algorithms
- Pattern Searching
- Geometric Algorithms
- Mathematical
- Bitwise Algorithms
- Randomized Algorithms
- Greedy Algorithms
- Dynamic Programming
- Divide and Conquer
- Backtracking
- Branch and Bound
- All Algorithms
- Company Preparation
- Practice Company Questions
- Interview Experiences
- Experienced Interviews
- Internship Interviews
- Competitive Programming
- Design Patterns
- System Design Tutorial
- Multiple Choice Quizzes
- Go Language
- Tailwind CSS
- Foundation CSS
- Materialize CSS
- Semantic UI
- Angular PrimeNG
- Angular ngx Bootstrap
- jQuery Mobile
- jQuery EasyUI
- React Bootstrap
- React Rebass
- React Desktop
- React Suite
- ReactJS Evergreen
- ReactJS Reactstrap
- BlueprintJS
- TensorFlow.js
- English Grammar
- School Programming
- Number System
- Trigonometry
- Probability
- Mensuration
- Class 8 Syllabus
- Class 9 Syllabus
- Class 10 Syllabus
- Class 11 Syllabus
- Class 8 Notes
- Class 9 Notes
- Class 10 Notes
- Class 11 Notes
- Class 12 Notes
- Class 8 Formulas
- Class 9 Formulas
- Class 10 Formulas
- Class 11 Formulas
- Class 8 Maths Solution
- Class 9 Maths Solution
- Class 10 Maths Solution
- Class 11 Maths Solution
- Class 12 Maths Solution
- Class 7 Notes
- History Class 7
- History Class 8
- History Class 9
- Geo. Class 7
- Geo. Class 8
- Geo. Class 9
- Civics Class 7
- Civics Class 8
- Business Studies (Class 11th)
- Microeconomics (Class 11th)
- Statistics for Economics (Class 11th)
- Business Studies (Class 12th)
- Accountancy (Class 12th)
- Macroeconomics (Class 12th)
- Machine Learning
- Data Science
- Mathematics
- Operating System
- Computer Networks
- Computer Organization and Architecture
- Theory of Computation
- Compiler Design
- Digital Logic
- Software Engineering
- GATE 2024 Live Course
- GATE Computer Science Notes
- Last Minute Notes
- GATE CS Solved Papers
- GATE CS Original Papers and Official Keys
- GATE CS 2023 Syllabus
- Important Topics for GATE CS
- GATE 2023 Important Dates
- Software Design Patterns
- HTML Cheat Sheet
- CSS Cheat Sheet
- Bootstrap Cheat Sheet
- JS Cheat Sheet
- jQuery Cheat Sheet
- Angular Cheat Sheet
- Facebook SDE Sheet
- Amazon SDE Sheet
- Apple SDE Sheet
- Netflix SDE Sheet
- Google SDE Sheet
- Wipro Coding Sheet
- Infosys Coding Sheet
- TCS Coding Sheet
- Cognizant Coding Sheet
- HCL Coding Sheet
- FAANG Coding Sheet
- Love Babbar Sheet
- Mass Recruiter Sheet
- Product-Based Coding Sheet
- Company-Wise Preparation Sheet
- Array Sheet
- String Sheet
- Graph Sheet
- ISRO CS Original Papers and Official Keys
- ISRO CS Solved Papers
- ISRO CS Syllabus for Scientist/Engineer Exam
- UGC NET CS Notes Paper II
- UGC NET CS Notes Paper III
- UGC NET CS Solved Papers
- Campus Ambassador Program
- School Ambassador Program
- Geek of the Month
- Campus Geek of the Month
- Placement Course
- Testimonials
- Student Chapter
- Geek on the Top
- Geography Notes
- History Notes
- Science & Tech. Notes
- Ethics Notes
- Polity Notes
- Economics Notes
- UPSC Previous Year Papers
- SSC CGL Syllabus
- General Studies
- Subjectwise Practice Papers
- Previous Year Papers
- SBI Clerk Syllabus
- General Awareness
- Quantitative Aptitude
- Reasoning Ability
- SBI Clerk Practice Papers
- SBI PO Syllabus
- SBI PO Practice Papers
- IBPS PO 2022 Syllabus
- English Notes
- Reasoning Notes
- Mock Question Papers
- IBPS Clerk Syllabus
- Apply for a Job
- Apply through Jobathon
- Hire through Jobathon
- All DSA Problems
- Problem of the Day
- GFG SDE Sheet
- Top 50 Array Problems
- Top 50 String Problems
- Top 50 Tree Problems
- Top 50 Graph Problems
- Top 50 DP Problems
- Solving For India-Hackthon
- GFG Weekly Coding Contest
- Job-A-Thon: Hiring Challenge
- BiWizard School Contest
- All Contests and Events
- Saved Videos
- What's New ?
- Data Structures
- Interview Preparation
- Topic-wise Practice
- Latest Blogs
- Write & Earn
- Web Development
Related Articles
- Write Articles
- Pick Topics to write
- Guidelines to Write
- Get Technical Writing Internship
- Write an Interview Experience
- Spring @Component Annotation with Example
- Spring @Autowired Annotation
Spring @Repository Annotation with Example
- Spring @Controller Annotation with Example
- Spring – REST Controller
- Difference between Cloud Architecture and Cloud Engineering
- Difference Between @Controller and @RestController Annotation in Spring
- Spring @ResponseBody Annotation with Example
- Constructor Chaining In Java with Examples
- Private Constructors and Singleton Classes in Java
- Java Interview Questions on Constructors
- Java Singleton Class
- Java Singleton Design Pattern Practices with Examples
- How to prevent Singleton Pattern from Reflection, Serialization and Cloning?
- Decorator Pattern | Set 1 (Background)
- The Decorator Pattern | Set 2 (Introduction and Design)
- Decorator Pattern | Set 3 (Coding the Design)
- Strategy Pattern | Set 1 (Introduction)
- Strategy Pattern | Set 2 (Implementation)
- Adapter Pattern
- Command Pattern
- Iterator Pattern
- Implementing Iterator pattern of a single Linked List
- Move all occurrences of an element to end in a linked list
- Remove all occurrences of duplicates from a sorted Linked List
- Arrays in Java
- Spring Boot - Start/Stop a Kafka Listener Dynamically
- Parse Nested User-Defined Functions using Spring Expression Language (SpEL)
- Split() String method in Java with examples
- Arrays.sort() in Java with examples
- Last Updated : 03 Dec, 2021
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier than compared to classic Java frameworks and application programming interfaces (APIs), such as Java database connectivity (JDBC), JavaServer Pages(JSP), and Java Servlet. This framework uses various new techniques such as Aspect-Oriented Programming (AOP), Plain Old Java Object (POJO), and dependency injection (DI), to develop enterprise applications. Now talking about Spring Annotation
Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program.
There are many annotations are available in Spring Framework. Some of the Spring Framework Annotations are listed below as follows where here we are going to discuss one of the most important annotations that is @Repository Annotation
- @Configuration
- @ComponentScan
- @Controller
- @Repository, etc.
@Repository Annotation
@Repository Annotation is a specialization of @Component annotation which is used to indicate that the class provides the mechanism for storage, retrieval, update, delete and search operation on objects. Though it is a specialization of @Component annotation, so Spring Repository classes are autodetected by spring framework through classpath scanning. This annotation is a general-purpose stereotype annotation which very close to the DAO pattern where DAO classes are responsible for providing CRUD operations on database tables.
Step 1: Create a Simple Spring Boot Project
Refer to this article Create and Setup Spring Boot Project in Eclipse IDE and create a simple spring boot project.
Step 2: Add the spring-context dependency in your pom.xml file. Go to the pom.xml file inside your project and add the following spring-context dependency.
Step 3: In your project create two packages and name the package as “entity” and “repository”. In the entity, package creates a class name it as Student. In the repository, the package creates a Generic Interface named as DemoRepository and a class name it as StudentRepository. This is going to be our final project structure.
Step 4: Create an entity class for which we will implement a spring repository. Here our entity class is Student. Below is the code for the Student.java file. This is a simple POJO (Plain Old Java Object) class in java.
Step 5: Before implementing the Repository class we have created a generic DemoRepository interface to provide the contract for our repository class to implement. Below is the code for the DemoRepository.java file.
Step 6: Now let’s look at our StudentRepository class implementation.
In this StudentRepository.java file, you can notice that we have added the @Repository annotation to indicate that the class provides the mechanism for storage, retrieval, update, delete and search operation on objects.
Note : Here we have used an in-memory Map to store the object data, you can use any other mechanisms too. In the real world, we use Databases to store object data.
Step 7: Spring Repository Test
So now our Spring Repository is ready, let’s test it out. Go to the DemoApplication.java file and refer to the below code.
Output: Lastly, run your application and you should get the following output as shown below as follows:
Please Login to comment...
- Java-Spring
New Course Launch!
Improve your Coding Skills with Practice
Start your coding journey now.
- Skip to primary navigation
- Skip to main content
- Skip to primary sidebar

Java Tutorial Blog
- Spring Tutorials
- Spring 4 Tutorials
- Spring Boot
- JSF Tutorials
- Binary Search Tree Traversal
- Spring Batch Tutorial
- AngularJS + Spring MVC
- Spring Data JPA Tutorial
- Packaging and Deploying Node.js
- Join Us (JBC)
@Resource, @PostConstruct and @PreDestroy Annotations Example
April 21, 2013 // by Manisha Patil // Leave a Comment
In this post I shall cover the JSR250 annotations. Introduced in Spring 2.5 , it added support for JSR-250 based annotations which include @Resource , @PostConstruct and @PreDestroy annotations. In my previous articles I have explained about the some of the popular annotations in Spring @Required , @Autowired and @Qualifier . Also please read about How to write Custom Spring Callback Methods?

@Resource vs @Autowired
@Resource is similar to @Autowired in functionality. @Autowired is Spring’s Annotation(only usable in Spring) whereas @Resource is JSR-250 Common Annotation equivalent (works the same in Java EE 5). Though the functionality for the two annotations being same, @Autowired is the only annotation that you can put on constructors.
By default auto wiring is done by object type . If you have two beans of the same type, then there is ambiguity that Spring can’t figure out which of the two beans to inject. That is when @Qualifier is used. It helps fix the ambiguity and tell Spring which of the two beans to inject. Use @Qualifier with @Autowired. With @Resource you can just put the bean name in the annotation as an attribute.
@PostConstruct and @PreDestroy
These annotations are alternative methods for defining initialization and destruction callback functions which I covered in post Customizing callback methods .
Example using @Resource, @PostConstruct and @PreDestroy
The example in post, demostrates the use of @Resource, @PostConstruct and @PreDestroy annotations.
Let us have working Eclipse IDE in place and follow the following steps to create a Spring application:
- Create a project : Create a project with a name SpringAnnotationExamples and create a package com.javabeat.jsrannotations under the src directory in the created project.
- Add Libraries : Add required Spring libraries using Add External JARs option as explained in the article Customizing callback methods .
- Create source files : Create Java classes Product,Type and MainApp under the com.javabeat.jsrannotations package.
- Create configuration file : Create XML based configuration file BeansJSRAnnotation.xml under src directory.
The class Product.java, is simple POJO class having name,price and an object of Type class. Contents of Product.java are:
import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.annotation.Resource;
public class Product { private Integer price; private String name;
@Resource(name = "typeB") private Type type;
public Integer getPrice() { return price; }
public void setPrice(Integer price) { this.price = price; }
public Type getType() { return type; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
@PostConstruct public void init() { System.out.println("In init block of Product"); }
Here you note that we have used @Resource annotation. @PostConstruct and @PreDestroy are used for their respective lifecycle callback methods. Here you can see, I’ve used the @Qualifier annotation alongwith the @Autowired annotation.
The Type.java class is also a POJO class having a string object called “type”. Contents of Type.java are:
public class Type {
private String productType;
public String getProductType() { return productType; }
public void setProductType(String productType) { this.productType = productType; }
Contents of MainApp are:
import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp { public static void main(String[] args) { AbstractApplicationContext context = new ClassPathXmlApplicationContext( "BeansJSRAnnotation.xml");
Product product = (Product) context.getBean("product");
System.out.println("Product Name : " + product.getName()); System.out.println("Price : " + product.getPrice());
Type productType = product.getType();
Here you need to register a shutdown hook registerShutdownHook() method that is declared on the AbstractApplicationContext class. This will ensures a graceful shutdown and calls the relevant destroy methods.
Contents of BeansJSRAnnotation.xml are:
<context:annotation-config />
As you can note here we are having two beans of same type.In Product.java I’ve used @Resource(“typeB”) it means we want to autowire Type property of Product with bean id=”typeB” in XML configuration file. You can also note that init-method and destroy-method attribute are used to specify the name of the method that has a return void, no argument method signature (init() and destroy method respectively from Product.java).
- Spring Aspect Oriented Programming (AOP)
Execute the code
The final step is run the application. Once all the above code is ready execute and the below output appears on the console:
- @Qualifier Annotation in Spring
- @Autowired Annotation in Spring
- @Required Annotation in Spring
In this post I discussed with and example about the use of JSR250 annotations. In the next article I shall cover the JSR330 annotations( @Inject and @Named ). If you are interested in receiving the future articles, please subscribe here .
About Manisha Patil
Manisha S Patil, currently residing at Pune India. She is currently working as freelance writer for websites. She had earlier worked at Caritor Bangalore, TCS Bangalore and Sungard Pune. She has 5 years of experience in Java/J2EE technologies.

Reader Interactions
Leave a reply cancel reply.
Your email address will not be published. Required fields are marked *
This site uses Akismet to reduce spam. Learn how your comment data is processed .

Java Guides
Search this blog, spring @importresource annotation example, create and import spring boot application.
The pom.xml File
Message.java, messageservice.java, emailservice.java, smsservice.java, twitterservice.java, messageprocessor.java, messageprocessorimpl.java, the applicationcontext.xml file, running application.
Read 25+ Spring Boot Articles with Source Code on GitHub - Spring Boot Tutorial
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course
Post a Comment
Copyright © 2018 - 2022 Java Guides All rights reversed | Privacy Policy | Contact | About Me | YouTube | GitHub

IMAGES
VIDEO
COMMENTS
The @Resource annotation is part of the JSR-250 annotation collection, and is packaged with Jakarta EE. This annotation has the following execution paths, listed by precedence: Match by Name Match by Type Match by Qualifier These execution paths are applicable to both setter and field injection. 2.1. Field Injection
The @Resource annotation in spring performs the autowiring functionality. This annotation follows the autowire=byName semantics in the XML based configuration i.e. it takes the name attribute for the injection. Below snippet shows how to use this annotation. Code Snippet This annotation takes an optional name argument.
The @Resource annotation is used to declare a reference to a resource. The @Resource annotation resolves dependency injection. We can use it in place of @Autowired annotation. 3. In case of field-based and method-based injection, the Spring container will inject the resource when the application is initialized.
@Resource is the annotation that will help to extract beans from the container. There are several lookup options to extract beans: Match by Name Match by Type Match by Qualifier Using @Resource without any parameters will trigger Match by Type lookup type.
1. Overview. We can leverage the capabilities of Spring DI engine using the annotations in the org.springframework.beans.factory.annotation and org.springframework.context.annotation packages. We often call these "Spring core annotations" and we'll review them in this tutorial. 2. DI-Related Annotations. 2.1. @Autowired.
In this example, both methods return the same Employee type. The bean that Spring will inject is the one returned by the method tonyEmployee . This is because it contains the @Primary annotation. This annotation is useful when we want to specify which bean of a certain type should be injected by default.
Spring supports Java SE Common Annotations (JSR-250).That means, we can use @Resource instead of using the combination of @Autowire and @Qualifier.. Example package com.logicbig.example.service; public interface OrderService { String getOrderDetails(String orderId); }
Spring Annotation Style Best Practices. Explicitly name your component [@Component("beanName")] Use '@Resource' with the 'name' attribute [@Resource(name="beanName")] Avoid '@Qualifier' annotations unless you want to create a list of similar beans. For example you may want to mark a set of rules with a specific '@Qualifier' annotation.
Spring @PostConstruct Annotation So generally, whenever we annotate a method in Spring Bean with @PostConstruct annotation, it gets executed after the spring bean is initialized. We can have only one method annotated with @PostConstruct annotation. This annotation is part of Common Annotations API and it's part of JDK module javax.annotation-api .
Spring @Value Annotation with Example Implementation: Step 1: First, let's create a simple Spring Application and inject the literal values by setter injection. So, create a simple class Student having three attributes rollNo, name, and age. Create setter methods for these two attributes and a simple method to print the details of the student.
@Resource annotation in Spring Matches by Name Matches by Type Restricts by Qualifiers (ignored if match is found by name) So you can see in case of @Autowired and @Inject switch to "byType" happens only after restricting by Qualifier. Whereas with @Resource it switches to byType if it doesn't find the bean by name.
For example, Spring 2.0 introduced the possibility of enforcing required properties with the @Required annotation. As of Spring 2.5, it is now possible to follow that same general approach to drive Spring's dependency injection. ... Instead, prefer the JSR-250 @Resource annotation which is semantically defined to identify a specific target ...
For example, Spring 2.0 introduced the possibility of enforcing required properties with the @Required annotation. As of Spring 2.5, it is now possible to follow that same general approach to drive Spring's dependency injection. ... Instead, use the JSR-250 @Resource annotation, which is semantically defined to identify a specific target ...
Resource Injection. The javax.annotation.Resource annotation is used to declare a reference to a [email protected] can decorate a class, a field, or a method. The container will inject the resource referred to by @Resource into the component either at runtime or when the component is initialized, depending on whether field/method injection or class injection is used.
This page contains a collection of commonly used Spring and Spring boot annotations with examples. Each Spring annotation is explained with source code examples and its usage. ... The PUT HTTP method is used to update the resource and @PutMapping annotation for mapping HTTP PUT requests onto specific handler methods.
With field-based and method-based injection, the container will inject the resource when the application is initialized. For class-based injection, the resource is looked up by the application at runtime. The @Resource annotation has the following elements: name: The JNDI name of the resource. type: The Java language type of the resource.
Step 2: Add the spring-context dependency in your pom.xml file. Go to the pom.xml file inside your project and add the following spring-context dependency. Step 3: In your project create two packages and name the package as "entity" and "repository". In the entity, package creates a class name it as Student.
@Resource is similar to @Autowired in functionality. @Autowired is Spring's Annotation(only usable in Spring) whereas @Resource is JSR-250 Common Annotation equivalent (works the same in Java EE 5). Though the functionality for the two annotations being same, @Autowired is the only annotation that you can put on constructors.
Spring provides a @ImportResource annotation is used to load beans from an applicationContext.xml file into an Application Context. @ImportResource ( { "classpath*:applicationContext.xml" }) In this example, we are creating a simple message processing spring boot application. Here we are sending a message using different services like ...