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

How @Resources annotation works

I am studying @Resource, @Resources injection in java. Oracle docs and some other sites are explaining field, method and class resource injection with @Resource annotation but I could not find help for Multiple class resources injection using @Resources annotation - Actually I want to know how multiple resources declared by @Resources annotation on class will be used in class? Example I am seeing on oracle docs on other sites is below:

But how i will use myMessageQueue and myMailSession in class body? So anyone can explain class body implementation or sample method implementation showing the usage of above declared resources by @Resources annotation?

nwzhaider's user avatar

Basically, @Resources is just an array of resource and inject the resource inside that array to your class during runtime.

EDIT The following code is from the implement from org.apache.cxf.common.injection.ResourceInjector

You can see in line89, it loops through the Resources array and inject the Resources. Btw, you can get the Resources array by Resource[] resoruces = CLASS_NAME.class.getAnnotation(Resources.class).value();

R.yan'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 resources or ask your own question .

Hot Network Questions

@resource annotation data source

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 .

@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

3 Using DataSource Resource Definitions

This chapter includes the following sections:

Using Java EE DataSource Resource Definitions

Using weblogic configuration attributes, implementation considerations when using datasource resource definitions, using data sources in clients, additional resources.

DataSource resources are used to define a set of properties required to identify and access a database through the JDBC API. These properties include information such as the URL of the database server, the name of the database, and the network protocol to use to communicate with the server. DataSource objects are registered with the Java Naming and Directory Interface (JNDI) naming service so that applications can use the JNDI API to access a DataSource object to make a connection with a database.

Prior to Java EE 7, DataSource resources were created administratively as described in Configuring WebLogic JDBC Resources in Administering JDBC Data Sources for Oracle WebLogic Server . Java EE 7 provides the option to programmatically define DataSource resources for a more flexible and portable method of database connectivity.

The name element uniquely identifies a DataSource and is registered with JNDI. The value specified in the name element begins with a namespace scope. Java EE 7 includes the following scopes:

java:comp —Names in this namespace have per-component visibility.

java:module —Names in this namespace are shared by all components in a module, for example, the EJB components defined in an a ejb-jar.xml file.

java:app —Names in this namespace are shared by all components and modules in an application, for example, the application-client, web, and EJB components in an .ear file.

java:global —Names in this namespace are shared by all the applications in the server.

You can programmatically declare DataSource definitions using one of the following methods:

Creating DataSource Resource Definitions Using Annotations

Creating datasource resource definitions using deployment descriptors.

The javax.annotation.sql package provides @DataSourceDefinition and @DataSourceDefinitions for defining DataSource resource definitions in application component classes such as application clients, servlets, or Enterprise JavaBeans (EJB).

When the DataSource resource is injected, a DataSource object is created and registered with JNDI. Use annotation elements to configure the DataSource object. You can specify additional Java EE and WebLogic configuration attributes in the properties element of the annotation. See Using WebLogic Configuration Attributes .

Use @DataSourceDefinition to create a single datasource definition. For example:

Use the @DataSourceDefinitions to create multiple datasource definitions. For example:

For a complete example, see the "Creating a DataSource using the @DataSourceDefinition Annotation" in the WebLogic Server Code Examples.

You can create DataSource resource definitions using deployment descriptors in application.xml , application-client.xml , web.xml , and ejb-jar.xml files. For example:

The Java EE 7 @DataSourceDefinition provides a basic standard set of configuration attributes. Oracle extends support for WebLogic Server's rich set of configuration attributes by supporting proprietary attributes using the property element.

Consider the following limitations when using WebLogic Server proprietary attributes in the property element. WebLogic Server proprietary attributes:

Cannot be used to configure a Multi data source. It is not possible to embed a Multi data source in a EAR or WAR file.

Do not overlap @DataSourceDefinition annotation elements.

Do not include the data source level attributes name and version .

Table 3-1 summarizes WebLogic Server's extended support for Data Source configuration attributes by mapping Weblogic.Attribute Name property values to WebLogic configuration elements. For an example of a DataSource resource definition using WebLogic configuration elements, see Configuring Active GridLink DataSource Resource Definitions .

Table 3-1 WebLogic Configuration Attributes

The following sections provide implementation details to consider when creating and using DataSource resource definitions:

Naming Conventions

Mapping the java ee datasource resource definition to weblogic data source resources, configuring active gridlink datasource resource definitions, using an encrypted password in a datasourcedefinition, additional considerations.

This section provides information on Data Source naming conventions:

Pre-WebLogic Server 12.1.1 and Java EE Data Source naming conventions are compatible. Existing applications do not need to change naming conventions to upgrade from previous releases.

WebLogic Data Source Naming Conventions

The following conventions are used when naming Data Sources in releases prior to WebLogic Server 12.1.1:

dsname - The system resource JDBC descriptor ( config/jdbc/*-jdbc.xml )

application @[email protected] dsname - deprecated (pre-9.x), application-scoped JDBC descriptor in EAR

application @ module @ dsname - application-scoped, packaged JDBC descriptor in EAR

Java EE Data Source Naming Conventions

The following conventions are used to name Java EE Data Sources:

appname @ modulename @ componentname @ dsname - Component level

appname @ modulename @ dsname - Module level

appname @ dsname - Application level

dsname – Global

These names are compatible with earlier names because the Java EE names begin with java:

Table 3-2 provides information on how to map Java EE DataSource Resource definition elements to WebLogic Server resources.

Table 3-2 Mapping a DataSource Resource Definition to WebLogic Server Resources

An Active GridLink Data Source is defined by using the following name/value pair within the DataSource resource definition:

FanEnabled is set to true

OnsNodeList is a non-null value. A comma-separated list of ONS daemon listen addresses and ports for receiving ONS-based FAN events. See ONS Client Configuration in Administering JDBC Data Sources for Oracle WebLogic Server .

The following example shows a DataSource resource definition for an Active GridLink Data Source using deployment descriptors:

For additional information, see Using Active GridLink Data Sources in Administering JDBC Data Sources for Oracle WebLogic Server .

You can provide an encrypted password in the DataSourceDefinition . To do so you need to generate the password as shown in the following example, and then copy it into the DataSourceDefinition :

The encrypted password is domain specific. If you use an encrypted password that does not match the domain, it will generate an error such as:

The following code fragment defines a data source using an encrypted password in an annotation in a Java servlet.

Consider the following when using a Java EE DataSource resource definition with WebLogic Server:

If an annotation and a descriptor have the same DataSource name in the same scope, the attributes are merged with values specified in the deployment descriptor. The deployment descriptor value takes precedence over values specified in a annotation.

A DataSource is not a module, it is a resource created as part of a module.

A DataSource is not a JDBCSystemResources object associated with a domain and is not in the WebLogic Server configuration bean tree.

You can use the JSR88 API's to view applications that include Java EE 7 Data Sources.

There is one runtime MBean created for each datasource definition. The name of the MBean is the decorated name.

WLS has a limited set of known class names for which it can generate a URL. For the non-XA case, the JDBC driver and not the datasource class is often known. An error occurs when an unknown class name is specified with a databaseName , portNumber , and/or serverName . In this case, remove databaseName , portNumber, serverName , and specify the URL.

URL generation is not supported for AGL data sources.

URL generation in general is a problem for all Oracle drivers because of the service, database, and Oracle RAC instance formats. The best practice is to provide the URL for Oracle drivers

You can implement Java EE Data Sources in a Java EE client. However:

Transactional=true is not supported. The transaction protocol is set to NONE .

Data Sources that are global or application in scope are visible (created) both on the client and the server. This has the downside of using more connections.

No permission checking is performed on a Data Source. Operations such as reserve and shrink can be used on a local Data Source.

This section provides additional resources for review when implementing DataSource resource definitions:

Section EE.5.17 "DataSource Resource Definition" in the Java EE 7 Specification at http://jcp.org/en/jsr/detail?id=316 .

The Java EE 7 Tutorial at http://docs.oracle.com/javaee/6/tutorial/doc/ .

JDBC™ 4.1 Specification at http://download.oracle.com/otn-pub/jcp/jdbc-4_1-mrel-spec/jdbc4.1-fr-spec.pdf .

WebLogic Server Code Examples.

Scripting on this page enhances content navigation, but does not change the content in any way.

Resource Injection

Resource injection enables you to inject any resource available in the JNDI namespace into any container-managed object, such as a servlet, an enterprise bean, or a managed bean. For example, you can use resource injection to inject data sources, connectors, or custom resources available in the JNDI namespace.

The type you use for the reference to the injected instance is usually an interface, which decouples your code from the implementation of the resource.

For example, the following code injects a data source object that provides connections to the default Apache Derby database shipped with GlassFish Server:

In addition to field-based injection as in the preceding example, you can inject resources using method-based injection:

To use method-based injection, the setter method must follow the JavaBeans conventions for property names: The method name must begin with set , have a void return type, and have only one parameter.

The @Resource annotation is in the javax.annotation package and is defined in JSR 250 (Common Annotations for the Java Platform). Resource injection resolves by name, so it is not typesafe: the type of the resource object is not known at compile time, so you can get runtime errors if the types of the object and its reference do not match.

Beta Draft (Pre-General Availability)

Configuring DataSources in tomee.xml share [gp] share [fb] share [tw] share [pin] contribute

The element is used to configure a javax.sql.DataSource . It is also used to configure other resources like Timers, Topics, Queues. We will see some examples of using to configure a DataSource.

The element is designed after @Resource annotation and has similar attributes.

For example, this annotation in your bean:

Would map to a Resource declared in your openejb.xml as follows:

Note that in the xml element, the type value of javax.sql.DataSource can abbreviated to just DataSource as follows:

It is also possible to specify the path to the driver jar file using a classpath attribute like so:

...Or in a Maven environment like so:

See Containers and Resources for a complete list of supported DataSource properties.

See DataSource Password Encryption for information on specifying non-plain-text database passwords in your openejb.xml file.

See Common DataSource Configurations for a list of the commonly used databases and their driver configurations.

See DataSource Configuration by Creator for a list of the different properties supported for each data source creator.

You may also need data partitioning per customer or depending on any other business criteria. That's also an available feature. See Dynamic Datasource for more details.

JNDI names for configured DataSources

The global jndi name would be java:openejb/Resource/Default JDBC Database

The global jndi name would be java:openejb/Resource/Derby Database

Obtaining a DataSource

DataSource references in your ejb should get automatically mapped to the Resource you declare. The shortest and easiest rule is that if your reference name matches a Resource in your openejb.xml, that's the one you get .  Essentially, the rules for mapping are as follows.

There are various ways one could obtain a DataSource now. Lets take an example of Derby.

With a Resource declaration in your openejb.xml like this:

There are several possible ways to refer to it, as follows.

BY matching variable name to resource name

OR BY matching name

OR BY JNDI lookup

Thank you for contributing to the documentation!

Any help with the documentation is greatly appreciated..

All edits are reviewed before going live, so feel free to do much more than fix typos or links. If you see a page that could benefit from an entire rewrite, we'd be thrilled to review it. Don't be surprised if we like it so much we ask you for help with other pages :)

Internet Explorer Users

If you are not an Apache committer, click the Yes link and enter a anonymous for the username and leave the password empty

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 data source

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 data source

Tomcat vs. Jetty vs. Undertow: Comparison of Spring Boot Embedded Servlet Containers

Using mockrestserviceserver to test a rest client, spring batch jobrepository example, load environment configurations and properties with spring example, spring framework jmstemplate example, 20 spring framework best practices, spring batch listeners example, how to write transactional unit tests with spring.

guest

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

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:

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:

Contents of MainApp are:

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:

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 .

DZone

Resource Injection vs. Dependency Injection Explained!

Lalit Rao user avatar

Join the DZone community and get the full member experience.

Fellow geeks, the following article provides an overview of injection in Java EE and describes the two injection mechanisms provided by the platform: Resource Injection and Dependency Injection.

Java EE provides injection mechanisms that enable our objects to obtain the references to resources and other dependencies without having to instantiate them directly (explicitly with ‘new’ keyword). We simply declare the needed resources & other dependencies in our classes by drawing fields or methods with annotations that denotes the injection point to the compiler.

The container then provides the required instances at runtime. The advantage of Injection is that it simplifies our code and decouples it from the implementations of its dependencies.

Note should be given for the fact that Dependency Injection is a specification (also a design pattern) and Context and Dependency Injection (CDI) is an implementation andJava standard for DI.

The following topics are discussed here:

·  Resource Injection

·  Dependency Injection

·  Difference between Context and Dependency Injection

1.   Resource Injection

One of the simplification features of Java EE is the implementation of basic Resource Injection to simplify web and EJB components.

Resource injection enables you to inject any resource available in the JNDI namespace into any container-managed object, such as a servlet, an enterprise bean, or a managed bean. For eg, we can use resource injection to inject data sources, connectors, or any other desired resources available in the JNDI namespace.

The type we’ll use for the reference to the instance happen to be injected is usually an interface, which would decouple our code from the implementation of the resource.

For better understanding of the above statement let’s take a look at the example.

The resource injection can be performed in the following three ways:

·  Field Injection

·  Method Injection

·  Class injection

Now, the  javax.annotation.Resource annotation is used to declare a reference to a resource. So before proceeding, let’s learn few elements of @Resource annotation.

@Resource has the following elements:

·  name: The JNDI name of the resource

·  type: The Java  type of the resource

·  authenticationType: The authentication type to use for the resource

·  shareable: Indicates whether the resource can be shared

·  mappedName: A non-portable, implementation-specific name to which the resource should be mapped

·  description: The description of the resource

Thenameelement is the JNDI name of the resource, and is optional for field- and method-based injection. For field injection, d defaultnameis the field name. For method-based injection, the defaultnameis the JavaBeans property name based on the method.

The‘name’ and ‘type’element must be specified for class injection.

Thedescriptionelement is the description of the resource (optional).

Let’s hop on to the example now.

Field Injection:

To use field-based resource injection, declare a field and annotate it with the @Resource annotation. The container will refer 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 code above, the container infers the name of the resource based on the class name and the field name: com.example.SomeClass/myDB. The inferred type isjavax.sql.DataSource.class.

In the code above, the JNDI name is customerDB, and the inferred type is javax.sql.DataSource.class.

Method Injection:

To use method injection, declare a setter method and preceding with the @Resource annotation. The container will itself refer the name and type of the resource if in case it is not specified by programmer. 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 (needless to say :P).  Anyways, if you do specify the return type, it must match the field’s type declaration.

In the code above, the container refers the name of the resource according to the class name and the field name: com.example.SomeClass/myDB. The type which is javax.sql.DataSource.class.

Class Injection:

To use class-based injection, decorate the class with a @Resource annotation, and set the requiredname and type elements.

Declaring Multiple Resources

The  @Resources annotation is used to group together multiple  @Resource declarations for class injection only.

The code above shows the @Resources annotation containing two @Resource declarations. One is a JMS (Java Messagin Service) message queue, and the other is a JavaMail session.

2.  Dependency Injection

Dependency injection  enables us to turn regular Java classes into managed objects and to inject them into any other managed object (objects wich are managed by the container).

Using DI, our code can declare dependencies on any managed object. The container automatically provides instances of these dependencies at the injection points at runtime, n it also manages the lifecycle of these instances right from class loading to releasing it for Garbage Collection.

Dependency injection in Java EE defines scopes. For eg, a managed object that is only happen to respond to a single client request (such as a currency converter) has a different scope than a managed object that is needed to process multiple client requests within a session (such as a shopping cart). We can define managed objects (also called managed beans ) so that we can later inject by assigning a scope to a needed class:

Umlike resource injection, dependency injection is typesafe because it resolves by type . To decouple our code from the implementation of the managed bean, we can reference the injected instances using an interface type and have our managed bean (regular class controlled by container) implement that interface.

I wouldn’t like to discuss more on DI or better saying CDI since we already have a great article published on this.

3.   Difference between Resource Injection and Dependency Injection

The differences between the RI and DI are listed below.

1.  Resource Injection can inject JNDI Resources directly whereas Dependency Injection cannot.

2.  Dependency Injection can inject Regular Classes (managed bean) directly whereas Resource Injection cannot.

3.  Resource Injection resolves by resource name whereas Dependency Injectin resolves by type.

4.  Dependency Injection is typesafe whereas Resoiurce Injection is not .

Conclusion:

Thus we learnt concept on types on Injection in Java EE and the differences between them. Just a brief. There’s more to come

Opinions expressed by DZone contributors are their own.

Popular on DZone

Partner Resources

CONTRIBUTE ON DZONE

Let's be friends:

Circle.java

DrawingApp.java

Share this:

Related Posts

@resource annotation data source

Scaling and Parallel Processing in Spring Batch 2

ClassNotFoundException vs NoClassDefFoundError In Java

ClassNotFoundException vs NoClassDefFoundError In Java

What’s New in Spring Batch 3.0

What’s New in Spring Batch 3.0

@resource annotation data source

@RequestParam Annotation in Spring MVC with Example

Java – String valueOf() Method

Java – String valueOf() Method

Polymorphism in Java

Polymorphism in Java

About the author.

' src=

Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Jstobigdata Logo

Dependency Injection: @Autowired, @Resource and @Inject

Wiring in Spring

In Spring Framework, you can basically use any of the three annotations for Dependency Injection, namely @Autowired , @Resource and @Inject. The @Autowired annotation belongs to the core-spring, however, the other two belongs to the Java extension package @javax.annotation.Resource and @javax.inject.Inject .

We will look into the use of each of these annotations with a practical use case, to help you choose the one that best suits you.

Common example

I will use the same set of classes to understand the Injections using @Resource , @Inject and @Autowired . As you can see the abstract class FileReader is extended by 2 classes, PdfFileReader and WordFileReader . The below example is used to explore the wiring (Dependency Injection) in all the 3 cases.

The @Configuration annotation in ConfigWiring indicates that this is used as a source of bean definitions. As you rightfully observed, the FileReader is not annotated with @Component as it is an abstract class. There are two concrete classes that extend FileReader, PdfFileReader and WordFileReader . Spring provides stereotype @Component annotation which registers the class as spring managed component.

1. @Resource – Dependency Injection using JSR-250

The @Resource annotation is from JSR-250 specification, which means it is from javax.annotation.Resource . If you are using JDK8+, make sure to add the JSR-250 dependency jar in your maven/Gradle file.

The Resource annotation class definition looks as below. As you can see, it accepts two important parameters that are type and name . The @Target({TYPE, FIELD, METHOD}) indicates where the @Resource annotation can be used.

What is Dependency Ambiguity

All of the below codes uses common examples from above, where FileReader is an abstract class and there are 2 classes PdfFileReader and WordFileReader that extends FileReader.

When we want to inject a dependency, we can just annotate the property or its setter method with the @Resource annotation. The problem occurs when we have ambiguity . The code below throws NoUniqueBeanDefinitionException as we have 2 classes extending the FileReader .

The above code is the reason why we need to write code in such a way that there is no dependency ambiguity.

1.1. Resolve dependency by Name

For simplicity of understanding, I am using the @Resource annotation on the property, you should use them on setter for performance reasons. In the first example below, the field name pdfFileReader is used as the bean name to resolve the dependency.

You can also specify the bean name explicitly as shown below.

1.2. Resolve dependency by Type

Spring will try to resolve the dependency by name . However, it will not find any bean with this name so next, it tries to resolve by type. As we have WordFileReader bean already registered, spring will autodetect this type and resolve this field.

In the below code, Spring can neither detect the dependency by name nor resolve by type. Because there is ambiguity, type detection will fail with Exception BeanCreationException . So we will specify the type explicitly, type = PdfFileReader.class to inject PdfFileReader.

1.3. Resolve dependency by @Qualifier

Spring has this special @Qualifier annotation in which we can pass the name of the bean to be resolved.

2. @Inject – Dependency Injection using JSR-330

The @Inject annotation is from JSR-330 specification, which means it is from javax.inject.Inject . If you are using JDK8+, make sure to add the JSR-330 dependency jar in your pom/Gradle file.

The Inject annotation looks as follow, which means it can be used on the field, setter or constructor based annotations.

1. Resolve dependency by Type

In the below examples, I have used the annotation on the property fields. But in a real project, you should use it on setters or constructors due to performance reasons.

The example below fileReader is of the type PdfFileReader , so the dependency injection is straight forward.

2. Resolve by @Qualifier annotation

There are 2 implementations of the base class FileReader and they are as PdfFileReader and WordFileReader . To get rid of this ambiguity, you need to specify the bean name in @Qualifier annotation. The code @Qualifier("wordFileReader") below represents the same.

If you don’t specify the @Qualifier , you will end up reproducing the exception as below.

3. Resolve dependency by Name

The @Inject annotation detects the bean to be injected in 2 ways. First, if @Named("beanName") annotation is specified. Otherwise, the field name is used as the bean name. The @Named annotation is from JSR-330 javax.inject.* package and it is used to specify the bean name whose instance will be injected.

The line-6 represents the bean name detection using @Named annotation. On the other hand, line-17 represents the auto-detection by field name.

3. @Autowired – Dependency Injection in Spring style

The @Autowired annotation is similar to @Inject annotation. The only difference is @Inject is from JSR-330 specification, and the @Autowired is purely from the Spring framework.

The @Autowired annotation looks as below. As you can observe, @Autowired can be used on the constructor, setter, field and in the parameters as well.

The examples discussed below uses field-based dependency injection, but you should always use the setter based or constructor based injections in your application due to performance reasons.

Spring first tries to detect the bean to be injected by its type and do the DI. In the code below, spring simply injects PdfFileReader instance.

2. Resolve dependency by @Qualifier

When you have ambiguity, use the @Qualifier annotation to specify the bean name to be injected.

Spring @Autowired annotation can resolve the dependency by field name as discussed before. In this example, spring inject the bean with name wordFileReader .

Conclusion:

This article only focuses on the auto wiring part. I prefer using @Autowired or @Inject. If you want to understand the dependency injection and scopes etc in Spring, check out the respective articles.

The complete code example is available on GitHub, download the code and try it out. The test cases are located here and the common classes are here .

Share This Page, Choose Your Platform!

Leave a comment cancel reply.

Save my name, email, and website in this browser for the next time I comment.

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

〈  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

IMAGES

  1. Data Annotation Tools for Machine Learning: An Evolving Guide

    @resource annotation data source

  2. Data Annotation- Stepping stone to the technical era

    @resource annotation data source

  3. How to Implement Your Data Annotation Project

    @resource annotation data source

  4. Learning Spiral AI : Data Annotation & Data Labeling

    @resource annotation data source

  5. Data Annotation

    @resource annotation data source

  6. CRUD OPERATIONS IN ENTITY FRAMEWORK CORE

    @resource annotation data source

VIDEO

  1. Heidi Weinstein Talks About iMerit's Culture

  2. Introduction to Entity Schemas and Shape Expressions (Data Quality Days 2022)

  3. Generating Reports

  4. Export Annotationeer Annotation Data To PDF Using iText, Aspose, PDFBox

  5. Studio Overview

  6. Data Engineer Appreciation Day: Data Observability: The Next Frontier of Data Engineering

COMMENTS

  1. java

    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 Share Improve this answer Follow

  2. Resource (Java Platform SE 8 )

    Annotation Type Resource @Target ( value = { TYPE, FIELD, METHOD }) @Retention ( value = RUNTIME ) public @interface Resource The Resource annotation marks a resource that is needed by the application. This annotation may be applied to an application component class, or to fields or methods of the component class.

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

  4. java

    Basically, @Resources is just an array of resource and inject the resource inside that array to your class during runtime. package javax.annotation; import java.lang.annotation.*; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.*;

  5. @Resource Annotation in Spring

    The @Resource annotation is JSR-250 javax.annotation.Resource API. Some other JSR-250 annotations are @PostConstruct, and @PreDestroy . 2. 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.

  6. Using DataSource Resource Definitions

    Creating DataSource Resource Definitions Using Annotations The javax.annotation.sql package provides @DataSourceDefinition and @DataSourceDefinitions for defining DataSource resource definitions in application component classes such as application clients, servlets, or Enterprise JavaBeans (EJB).

  7. Resource Injection

    Resource Injection. Resource injection enables you to inject any resource available in the JNDI namespace into any container-managed object, such as a servlet, an enterprise bean, or a managed bean. For example, you can use resource injection to inject data sources, connectors, or custom resources available in the JNDI namespace. The type you ...

  8. Configuring DataSources in tomee.xml

    We will see some examples of using to configure a DataSource. The element is designed after @Resource annotation and has similar attributes. For example, this annotation in your bean: @Resource(name = "myDerbyDatasource", type = javax.sql.DataSource.class) Would map to a Resource declared in your openejb.xml as follows:

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

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

    Contents of Product.java are: 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".

  11. Resource Injection vs. Dependency Injection Explained!

    To use field-based resource injection, declare a field and annotate it with the @Resource annotation. The container will refer the name and type of the resource if the name and type...

  12. @Resource Annotation in JSR-250 with Spring Framework

    The @Resource annotation takes a ' name ' attribute which will be interpreted as the bean name to be injected. You can say, it follows by-name autowiring semantics as demonstrated in the below example: package com.dineshonjava.sdnext.jsr.tutorial; import javax.annotation.Resource; public class Circle { private Point center; @Resource (name ...

  13. Dependency Injection: @Autowired, @Resource and @Inject

    In Spring Framework, you can basically use any of the three annotations for Dependency Injection, namely @Autowired, @Resource and @Inject. The @Autowired annotation belongs to the core-spring, however, the other two belongs to the Java extension package @javax.annotation.Resource and @javax.inject.Inject. We will look into the use of each of ...

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