Examples Java Code Geeks

Spring @Resource Annotation Example

Photo of Yatin

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.

@resource annotation in spring example

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.

Spring @Resource Annotation - Application Project Structure

2.3 Project Creation

Spring @Resource Annotation - Create a Maven Project

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.

Spring @Resource Annotation - 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.

Photo of Yatin

Related Articles

@resource annotation in spring example

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.

guest

This site uses Akismet to reduce spam. Learn how your comment data is processed .

@Resource Annotation in Spring

@resource vs @autowired, @resource at field level, @resource at method level, @resource by type, download source code.

ARVIND RAI

Mobile Apps

Get it on Google Play

©2023 concretepage.com | Privacy Policy | Contact Us

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?

J-Alex's user avatar

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.

enter image description here

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:

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.

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

ThisIsntSparta's user avatar

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 .

Hot Network Questions

@resource annotation in spring example

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 .

〈  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

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

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

Strategy Direction

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

Making a Market

Material Market: Coordinating Distributed Events

Centralized Data

Reference Data Without the Database

image of Technology Background Datum Binary Matrix Abstract Code Coding Information Machine Learning ML AI Science Virtual Zero Pattern Vector

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.

Related Articles

Spring @Repository Annotation with Example

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

@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...

New Course Launch!

Improve your Coding Skills with Practice

Start your coding journey now.

JavaBeat

Java Tutorial Blog

@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?

JSR-250 Annotations Example

@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:

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).

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:

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 .

' src=

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.

New Features in Spring Boot 1.4

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

Java Guides

Search this blog, spring @importresource annotation example, create and import spring boot application.

@resource annotation in spring example

The pom.xml File

Message.java, messageservice.java, emailservice.java, smsservice.java, twitterservice.java, messageprocessor.java, messageprocessorimpl.java, the applicationcontext.xml file, running application.

@resource annotation in spring example

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

  1. Spring Annotations

    @resource annotation in spring example

  2. Spring annotation

    @resource annotation in spring example

  3. Useful Spring Annotation PDF

    @resource annotation in spring example

  4. Spring JDBC Annotation Example

    @resource annotation in spring example

  5. Spring Data JPA @Modifying Annotation Example

    @resource annotation in spring example

  6. Spring @RequestHeader Annotation Example

    @resource annotation in spring example

VIDEO

  1. Spring @Condition Annotation

  2. #22 Spring JDBC Java Based Annotation Crud Operation

  3. 51.Spring Core Annotations(part-4)

  4. Springboot class 7 Layered App program

  5. SPRING FRAMEWORK @PROPERTYSOURCE ANNOTATION DEMO

  6. Lec10-Spring Boot MVC REST Annotations With Examples

COMMENTS

  1. Wiring in Spring: @Autowired, @Resource and @Inject

    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

  2. Spring @Resource Annotation Example

    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.

  3. @Resource Annotation in Spring

    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.

  4. java

    @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.

  5. Spring Core Annotations

    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.

  6. Spring @Qualifier Annotation

    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.

  7. Spring

    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); }

  8. Spring Injection with @Resource, @Autowired and @Inject

    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.

  9. Spring

    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 .

  10. Spring @Required Annotation with Example

    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.

  11. @Resource Annotation in Spring Autowiring

    @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.

  12. 4.11 Annotation-based configuration

    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 ...

  13. 3.9 Annotation-based container configuration

    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 ...

  14. Resource Injection

    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.

  15. All Spring Annotations with Examples

    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.

  16. Resource Injection

    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.

  17. Spring @Repository Annotation with Example

    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.

  18. @Resource, @PostConstruct and @PreDestroy Annotations Example

    @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.

  19. Spring @ImportResource Annotation Example

    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 ...