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

Is it possible to use @Resource on a constructor?

I was wondering if it possible to use the @Resource annotation on a constructor.

My use case is that I want to wire a final field called bar .

I get a message that the @Resource is not allowed on this location. Is there any other way I could wire the final field?

entpnerd's user avatar

3 Answers 3

From the source of @Resource :

means that this annotation can only be placed on Classes, Fields and Methods. CONSTRUCTOR is missing.

Sean Patrick Floyd's user avatar

To complement Robert Munteanu's answer and for future reference, here is how the use of @Autowired and @Qualifier on constructor looks :

In this example, bar is just autowired (i.e. there is only one bean of that class in the context so Spring knows which to use), while baz has a qualifier to tell Spring which particular bean of that class we want injected.

Pierre Henry's user avatar

Use @Autowired or @Inject . This limitation is covered in the Spring reference documentation: Fine-tuning annotation-based autowiring with qualifiers :

@Autowired applies to fields, constructors, and multi-argument methods, allowing for narrowing through qualifier annotations at the parameter level. By contrast, @Resource is supported only for fields and bean property setter methods with a single argument. As a consequence, stick with qualifiers if your injection target is a constructor or a multi-argument method.

Robert Munteanu'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 spring autowired spring-annotations or ask your own question .

Hot Network Questions

spring resource annotation constructor

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 .

Why You Should Use Constructor Injection in Spring

Dependency injection is an approach to implement loose coupling among the classes in an application.

There are different ways of injecting dependencies and this article explains why constructor injection should be the preferred way.

Example Code

What is dependency injection.

Thus dependency injection helps in implementing inversion of control (IoC). This means that the responsibility of object creation and injecting the dependencies is given to the framework (i.e. Spring) instead of the class creating the dependency objects by itself.

We can implement dependency injection with:

Constructor Injection

In constructor-based injection, the dependencies required for the class are provided as arguments to the constructor:

Before Spring 4.3, we had to add an @Autowired annotation to the constructor. With newer versions, this is optional if the class has only one constructor.

In the Cake class above, since we have only one constructor, we don’t have to specify the @Autowired annotation. Consider the below example with two constructors:

When we have a class with multiple constructors, we need to explicitly add the @Autowired annotation to any one of the constructors so that Spring knows which constructor to use to inject the dependencies.

Setter Injection

In setter-based injection, we provide the required dependencies as field parameters to the class and the values are set using the setter methods of the properties. We have to annotate the setter method with the @Autowired annotation.

The Cake class requires an object of type Topping . The Topping object is provided as an argument in the setter method of that property:

Spring will find the @Autowired annotation and call the setter to inject the dependency.

Field Injection

With field-based injection, Spring assigns the required dependencies directly to the fields on annotating with @Autowired annotation.

In this example, we let Spring inject the Topping dependency via field injection:

Combining Field and Setter Injection

What will happen if we add @Autowired to both, a field and a setter? Which method will Spring use to inject the dependency?

In the above example, we have added the @Autowired annotation to both the setter and the field. In this case, Spring injects dependency using the setter injection method.

Note that it’s bad practice to mix injection types on a single class as it makes the code less readable.

Why Should I Use Constructor Injection?

Now that we have seen the different types of injection, let’s go through some of the advantages of using constructor injection.

All Required Dependencies Are Available at Initialization Time

We create an object by calling a constructor. If the constructor expects all required dependencies as parameters, then we can be 100% sure that the class will never be instantiated without its dependencies injected.

The IoC container makes sure that all the arguments provided in the constructor are available before passing them into the constructor . This helps in preventing the infamous NullPointerException .

Constructor injection is extremely useful since we do not have to write separate business logic everywhere to check if all the required dependencies are loaded, thus simplifying code complexity.

What About Optional Dependencies?

With setter injection, Spring allows us to specify optional dependencies by adding @Autowired(required = false) to a setter method. This is not possible with constructor injection since the required=false would be applied to all constructor arguments.

We can still provide optional dependencies with constructor injection using Java's Optional type.

Identifying Code Smells

Constructor injection helps us to identify if our bean is dependent on too many other objects. If our constructor has a large number of arguments this may be a sign that our class has too many responsibilities . We may want to think about refactoring our code to better address proper separation of concerns.

Preventing Errors in Tests

Constructor injection simplifies writing unit tests. The constructor forces us to provide valid objects for all dependencies. Using mocking libraries like Mockito, we can create mock objects that we can then pass into the constructor.

We can also pass mocks via setters, of course, but if we add a new dependency to a class, we may forget to call the setter in the test, potentially causing a NullPointerException in the test.

Constructor injection ensures that our test cases are executed only when all the dependencies are available. It’s not possible to have half created objects in unit tests (or anywhere else for that matter).


Constructor injection helps in creating immutable objects because a constructor’s signature is the only possible way to create objects. Once we create a bean, we cannot alter its dependencies anymore. With setter injection, it’s possible to inject the dependency after creation, thus leading to mutable objects which, among other things, may not be thread-safe in a multi-threaded environment and are harder to debug due to their mutability.

Constructor injection makes code more robust. It allows us to create immutable objects, preventing NullPointerException s and other errors.

You can find the code example on GitHub .

Vasudha Venkatesan

A budding software engineer curious to learn new things and open to innovative ideas.

Recent Posts

Getting started with spring security and spring boot.

Spring Security is a framework that helps secure enterprise applications. By integrating with Spring MVC, Spring Webflux or Spring Boot, we can create a powerful and highly customizable authentication and access-control framework.

Demystifying Transactions and Exceptions with Spring

One of the most convincing justifications for using the Spring Framework is its extensive transaction support. For transaction management, the Spring Framework offers a stable abstraction.

JUnit 5 Parameterized Tests

If you’re reading this article, it means you’re already well-versed with JUnit. Let me give you a summary of JUnit - In software development, we developers write code which does something simple as designing a person’s profile or as complex as making a payment (in a banking system).

17. Spring Beans and Dependency Injection

You are free to use any of the standard Spring Framework techniques to define your beans and their injected dependencies. For simplicity, we often find that using @ComponentScan (to find your beans) and using @Autowired (to do constructor injection) works well.

If you structure your code as suggested above (locating your application class in a root package), you can add @ComponentScan without any arguments. All of your application components ( @Component , @Service , @Repository , @Controller etc.) are automatically registered as Spring Beans.

The following example shows a @Service Bean that uses constructor injection to obtain a required RiskAssessor bean:

If a bean has one constructor, you can omit the @Autowired , as shown in the following example:

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 .


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 .

Spring Tutorial

Spring @Autowired Annotation

The @Autowired annotation provides more fine-grained control over where and how autowiring should be accomplished. The @Autowired annotation can be used to autowire bean on the setter method just like @Required annotation, constructor, a property or methods with arbitrary names and/or multiple arguments.

@Autowired on Setter Methods

You can use @Autowired annotation on setter methods to get rid of the <property> element in XML configuration file. When Spring finds an @Autowired annotation used with setter methods, it tries to perform byType autowiring on the method.

Let us have working Eclipse IDE in place and follow the following steps to create a Spring application −

Here is the content of TextEditor.java file −

Following is the content of another dependent class file SpellChecker.java :

Following is the content of the MainApp.java file −

Following is the configuration file Beans.xml −

Once you are done with creating source and bean configuration files, let us run the application. If everything is fine with your application, this will print the following message −

@Autowired on Properties

You can use @Autowired annotation on properties to get rid of the setter methods. When you will pass values of autowired properties using <property> Spring will automatically assign those properties with the passed values or references. So with the usage of @Autowired on properties your TextEditor.java file will become as follows −

Once you are done with the above two changes in source and bean configuration files, let us run the application. If everything is fine with your application, this will print the following message −

@Autowired on Constructors

You can apply @Autowired to constructors as well. A constructor @Autowired annotation indicates that the constructor should be autowired when creating the bean, even if no <constructor-arg> elements are used while configuring the bean in XML file. Let us check the following example.

Once you are done with the above two changes in source and bean configuration files, let us run the application. If everything is fine with your application, this will print the following message:

@Autowired with (required = false) option

By default, the @Autowired annotation implies the dependency is required similar to @Required annotation, however, you can turn off the default behavior by using (required=false) option with @Autowired.

The following example will work even if you do not pass any value for age property but still it will demand for name property. You can try this example yourself because this is similar to @Required annotation example except that only Student.java file has been changed.

// Tutorial //

Spring @autowired annotation.

Default avatar

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Spring @Autowired annotation is used for automatic dependency injection. Spring framework is built on dependency injection and we inject the class dependencies through spring bean configuration file.

spring @autowired annotation, @Autowired, spring autowiring, spring @autowired

Spring @Autowired, Spring autowiring, @Autowired annotation

Spring @Autowired Annotation - Maven Dependencies

For spring autowiring, we don’t need to add any additional dependencies. Our pom.xml file has spring framework core dependencies and looks like below.

Spring @Autowired Annotation - Model Bean

Let’s create a simple Java Bean, named Employee. This bean will have a single property with getter and setter methods. We will initialize this property value in the spring bean configuration file.

Spring @Autowired Annotation - Service Class

Let’s create our service class in which we will inject Employee bean through spring autowiring.

We will use the same service class for perform spring autowiring byName, byType and by constructor. The setter method will be used for spring autowiring byName and byType whereas constructor based injection will be used by constructor autowire attribute. When we use spring autowire byName or byType, default constructor is used. That’s why we have explicitly defined the default constructor for the EmployeeService bean.

Spring @Autowired Annotation - autowiring byType Example

Let’s create a separate class with Spring @Autowired annotation for autowiring byType.

Note that I have annotated both Employee variable and it’s setter method with Spring @Autowired annotation, however only one of these is sufficient for spring bean autowiring.

Spring @Autowired Annotation and @Qualifier Bean autowiring by constructor Example

Let’s create another service class where we will use @Autowired annotation for constructor based injection. We will also see @Qualifier annotation usage.

When this bean will be initialized by Spring framework, bean with name as “employee” will be used for autowiring. Spring @Autowired annotation excepts one argument “required” that is a boolean with default value as TRUE. We can define it to be “false” so that spring framework don’t throw any exception if no suitable bean is found for autowiring.

Spring @Autowired Annotation - Bean Configuration File

Spring bean configuration file is the main part of any spring application, let’s see how our spring bean configuration file looks and then we will look into each part of it.

Important points about spring bean configuration file are:

Spring @Autowired Annotation - Test Program

Now that our spring application is ready with all types of spring autowiring, let’s write a simple test program to see if it works as expected or not.

The program is simple, we are just creating the spring application context and using it to get different beans and printing the employee name. When we run above application, we get following output.

As you can see that for autowire byName and byType, default no-args constructor is used to initialize the bean. For autowire by constructor, parameter based constructor is used. From the hashcode of all the variables, we have confirmed that all the spring beans are different objects and not referring to the same object. Since we removed “employee1” from the list of eligible beans for autowiring, there was no confusion in the bean mapping. If we remove autowire-candidate="false" from the “employee1” definition, we will get below error message when executing the above main method.

That’s all for the Spring @Autowired Annotation and Spring autowiring feature, please download the example project from below link and analyse it to learn more.

Download Spring Bean Autowiring Project

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us

Still looking for an answer?

Hi Pankaj, Thank you for the tutorial. I have little confusion i.e if I have 2 beans in .xml file with names “employee” and “employee1” and as per employeeAutowiredByTypeService bean, It would create a bean of EmployeeAutowiredByTypeService.class till this part I am clear. Once you are getting this employeeAutowiredByTypeService obj and calling for “autowiredByTypeService.getEmployee().getName()”, then in such case which object would come because both “employee” and “employee1” are of type “Employee” how to solve this kind of collision, should we use @Qualifier (“nameOfBean”) annotation or by default does it pick up anyone? Please help me with this query.

- Raghu Ram

Description Resource Location Path Type ClassPathXmlApplicationContext cannot be resolved to a type SpringMain.java line 13 /SpringBeanAutowiring/src/main/java/com/journaldev/spring/autowiring/main Java Problem I am not able to find issue . please check

I hope I can get answer. I’m trying to create multiple object in bean configuration but it throws me an error It throws an exception of a conflict. But it doesn’t give any error when I instantiate random named service objects autowiredByConstructorService = ctx.getBean(“employeeAutowiredByConstructorService”,EmployeeAutowiredByConstructorService.class); w

Hi when your page reload it ask for allow for show notification. I want to implement the same on my website. My website is built on spring and jsp. Please help me to do. Thankyou

Above statement is wrong. It actually call the setter method. So if bean name is employee, it will call setEmployee method. Even if you change the property name to emp, it will work. Usually we make sure property name and bean name is same. Then just follow the naming convention of setter method. So it works and give impression that property name and bean name should be same.

If you write the configure your beans via javaConfig.java, instead of using .xml file that would be better.

- SprinfDev

Its nice explanation.

clean explanation sir

Thanks, nice post

- Binh Nguyen

how can i integrate webserices with spring framework

Creative Commons

Popular Topics

Try DigitalOcean for free

Join the tech talk.

Please complete your information!


  1. ozenero

    spring resource annotation constructor

  2. Apply @Resource Annotation in constructor in Spring Autowiring

    spring resource annotation constructor

  3. JAVA EE: Apply @Resource Annotation in constructor in Spring Autowiring

    spring resource annotation constructor

  4. Spring @Autowired Annotation with Example

    spring resource annotation constructor

  5. Spring Annotation Based Configuration

    spring resource annotation constructor

  6. Autowiring trong Spring, annotation @Autowired trong Spring

    spring resource annotation constructor


  1. Spring Making Machine-3-D Wire Bender-samples

  2. Spring @Condition Annotation

  3. @Repository Annotation


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

  6. 2.Spring framework introduction-PART2


  1. Is it possible to use @Resource on a constructor?

    Is there any other way I could wire the final field? java · spring · autowired · spring-annotations · Share.

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

    We can resolve dependencies by field injection by annotating an instance variable with the @Resource annotation. 2.1.1. Match by Name. We'll use

  3. Constructor Dependency Injection in Spring

    This quick tutorial will explore a specific type of DI technique within Spring called Constructor-Based Dependency Injection, which simply

  4. Why You Should Use Constructor Injection in Spring

    Before Spring 4.3, we had to add an @Autowired annotation to the constructor. With newer versions, this is optional if the class has only

  5. 6. Resources

    A UrlResource is created by Java code explicitly using the UrlResource constructor, but will often be created implicitly when you call an API method which takes

  6. 17. Spring Beans and Dependency Injection

    service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class

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

  8. Spring

    Spring supports Java SE Common Annotations (JSR-250). That means, we can use @Resource instead of using the combination of @Autowire and

  9. Spring @Autowired Annotation

    You can apply @Autowired to constructors as well. A constructor @Autowired annotation indicates that the constructor should be autowired when creating the bean

  10. Spring Dependency Injection

    AnnotationConfigApplicationContext constructor takes Class as argument that will be used to get the bean implementation to inject in component

  11. Spring @Autowired Annotation

    The setter method will be used for spring autowiring byName and byType whereas constructor based injection will be used by constructor autowire