IntelliJ IDEA shows errors when using Spring's @Autowired annotation
Asked Answered
B

33

150

IntelliJ IDEA is showing errors when I use Spring's @Autowired annotation in the class, but the class is functioning without any problem.

Here is this error message:

Autowired members must be defined in the valid spring bean (@Component/@Service,etc.) less... (Ctrl+F1) Checks autowiring problems in a bean class.

Baillargeon answered 24/1, 2014 at 2:28 Comment(7)
I have the same error for my integration test classes. I think using the @SupressWarnings annotation is a nice solution.Frequency
Intellij 2016.2 is doing this with my spring boot / spring data project. Which file is Intellij looking at to ascertain what beans exist?Karttikeya
There's at least one use-case they could exclude or refine, and that is when the relevant inspected class is abstract. I have the issue a lot where my abstract superclasses have a field or argument of type SomeBean<T>, where <T> is specified in subclassesSquid
For IntelliJ IDEA 2017.3.1 (Ultimate Edition) use @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")Adagietto
Just hit alt + enter on warning, then rigth arrow and select Suppress for class. Idea will add right @SuppressWarnings annotation automaticallyDutchman
For Kotlin and IDEA 2020.03 it's @Suppress("SpringJavaInjectionPointsAutowiringInspection") i.e. not @SuppressWarningsMarmawke
For my project this warning pointed to an different problem, that is that the class that contains the field was intended to be instantiated as a bean in a config service but it wasn't. I think what IntelliJ is detecting is that the class is never instantiated in a spring context and thus assumes that the @Autowire annotation was used wrongly. If I had followed the answers to just ignore the warning I would be screwing myself.Missis
F
38

I fixed it by adding the supress warning:

 @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
 @Autowired
 private ....
Fibula answered 2/8, 2018 at 0:7 Comment(5)
Or add the @SupressWarnings annotation to the class, if you have more than one @AutowiredAlarmist
You cannot call this a "solution".Ivon
@HonzaZidek Yes, which is why I downvoted and flagged this answer, as well as many others in this Q&A, for "not being an answer".Orpiment
@MehdiCharife You should not use 'not an answer' flags for this purpose. This does attempt to answer the question. You should only flag as NAA if the answer does not even attempt to answer the question, for example, if it is a followup question or a 'thank you' comment.Stash
@user16217248 I don't think this answer attempts to answer the question of "How to fix the issue that causes the warning". Instead, it attempts to answer the different question of "How to suppress this warning".Orpiment
S
34

I had the same problem with IntelliJ IDEA 13.1.4 I solved it by removing the Spring facet (File->Project Structure) and leaving it to just show "Detection".

Susy answered 19/1, 2015 at 17:25 Comment(2)
But what if you actually forget to annotate a bean. You won't get any warning?Mariehamn
But Maven->Reload all Maven Projects will bring the same problem back again.Volz
O
24

Got the same error here!

It seems the Intellij cannot verify if the class implementation is a @Service or @Component.

Solved it by just changing from Error to Warning(Pressing Alt + Enter).

Obtest answered 14/8, 2014 at 20:26 Comment(1)
"Solve it just changing from Error to Warning". You cannot call this a "solution".Ivon
S
24

If you know that the bean exists and its just a problem of the inspections, then just add the following before the variable declaration:

@SuppressWarnings("SpringJavaAutowiringInspection")
@Inject MyClass myVariable;

Sometimes IntelliJ cannot resolve if a bean has been declared, for example when the bean is included conditionally and the condition resolution happens dynamically at runtime. In such a case it seems the static code analyzer of IntelliJ cannot detect the bean.

Sixteenmo answered 21/4, 2016 at 11:11 Comment(0)
P
22

Remove .iml file from all your project module and next go to File -> Invalidate Caches/Restart

Paba answered 15/7, 2015 at 8:13 Comment(1)
Removing facets and suppressing warnings or similar "fixes" did not seem logical or smart so I gave this a shot. But I didn't do the last step the same. Instead I deleted my .iml file, chose to reimport in the maven options on the pom.xml file, and did a ctrl + s to regenerate the .iml. Errors gone.Fakieh
C
15

File -> ProjectStructure -> Modules -> +(in central column) -> Spring ->OK

Continuous answered 11/8, 2016 at 8:48 Comment(2)
which central column?Felodese
@KuldeepYadav with central column he probably means the column where you select the module to work with.Faviolafavonian
S
10

I have the same issue.

enter image description here

And I think the proper way to fix it is to tell Intellij to find the correct Spring Context, rather than "suppress warning".

In short, File -> ProjectStructure(⌘;) -> Modules -> (select the module) -> Spring -> (click '+' to add context) -> OK

enter image description here

Add the context file:

enter image description here

done!

enter image description here

Skit answered 3/10, 2021 at 22:42 Comment(0)
T
7

I had the same problem. I solved it by adding the Spring facet (File->Project Structure) for each relevant module, and then add the configuration files. For some projects (spring mvc), the config files where detected automatically. However, for a jar project, I had to add the configuration files manually.

Tizzy answered 26/6, 2015 at 15:44 Comment(0)
D
6

Solved the issue by going to File >> Project Structure >> Facets and then adding all the configuration files to Spring Facet. After that it started detecting files in which the beans reside and was able to sort the issue. IntelliJ giving this check is quite valuable and IMHO shouldn't be disabled.

Duleba answered 10/5, 2018 at 7:33 Comment(2)
I don't see Spring as a possible Facet. What version of Intellij do you have?Uel
@jDub9 it needs the ultimate (paid) version. The free version has no Spring integration.Faviolafavonian
P
6

I might be a little late, but after spending hours and researching on this issue.

I found out that in the latest version IntelliJ 2020 @AutoWired is optional and constructor based depedency injection is preferable.

I solved the problem by simply removing the @AutoWired Annotation from Service and Controller class and using constructor based dependency injection.

This link might help.

Happy Coding!

Pluvious answered 20/7, 2020 at 17:38 Comment(1)
This comment seems to be outdated, because IntelliJ now also warns when it can't find dependencies that are injected via constructor.Bacteriology
L
5

Make sure you have your Spring bean definitions correct. Sometimes, the application works fine, it just displays an error in the IDE, check your project ‘iml’ file if you have a Spring facet defined.

Lucy answered 24/1, 2014 at 2:44 Comment(7)
Also check your application-properties.xml. Check if line context:component-scan base-package=”com.my.project” does not exclude the package of the service you are referencing.Lucy
I put your code into the "bec-job.iml" of my project,but the problem still exists.And i can not find the file name is "applicationContext-interface.xml" in my project,can you tell about it in detail?Baillargeon
you must put @SuppressWarnings("SpringJavaAutowiringInspection") right above the @Autowired part of your code that is highlihgted red. This way IntelliJIdea recognise which warning to suppress.Lucy
you must find file "application-properties.xml", not "applicationContext-interface.xml"Lucy
example from my code: @SuppressWarnings("SpringJavaAutowiringInspection") @Autowired private MessageService messageService;Lucy
The problem has been resolved by put @SuppressWarnings("SpringJavaAutowiringInspection") right above the @Autowired part of my code ,i really appreciate your help.Thankyou very much.Baillargeon
That @SuppressWarnings("SpringJavaAutowiringInspection") seems hacky to me, but it works. Thanks guys.Sula
O
3

I had this problem too. Doing alt+enter and then asking to either re-run or disable Spring inspection on the effected line fixed it. This only seems to have become an issue after the 13.4 update.

Orji answered 30/7, 2014 at 17:29 Comment(0)
H
3

Suppressing the warning smells may not work as the warning can indicate that the instance was not injected, i.e. it's null.

If you are using Spring Boot:

  • What worked for me was annotating my test class with @SpringBootTest(ClassName.class) where < ClassName > is replaced with the name of the class being tested.
  • The annotation works by creating the ApplicationContext that will be used in the test, thereby recognising the @autowired annotation
Harewood answered 19/4, 2023 at 15:13 Comment(0)
V
2

I got the same problem. Mine was because the bean containing the autowired reference was not a Spring component (it was an EJB), but got a SpringBeanAutowiringInterceptor Interceptor allowing the use of autowiring. I think Intellij don't take this possibility in its Autowiring inspection.

Veronikaveronike answered 5/3, 2014 at 10:44 Comment(0)
M
2

It seems like the visibility problem - the parent controller doesn't see the Component you are trying to wire.

Try to add

@ComponentScan("path to respective Component") 

to the parent controller.

Mientao answered 26/10, 2015 at 23:7 Comment(0)
W
2

Make sure that your IntelliJ Idea (IDE) is aware of all the necessary spring configurations that your module is being inspected against.

You can check this under

File > Project Structure > Modules > [your project name in the right panel] > Spring

Sometimes, we need to explicitly tell the IDE that the spring configuration is coming from a dependency (a jar present in your project classpath)

Wofford answered 4/6, 2016 at 12:17 Comment(1)
is this available on the community edition or is it only on the ultimate?Brande
T
1

in my case I was missing to write in web.xml:

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>

   <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath*:applicationContext.xml</param-value>
   </context-param>

and in the application context file:

<context:component-scan base-package=[your package name] />

after add this tags and run maven to rebuild project the autowired error in intellj desapears and the bean icon appears in the left margin: enter image description here

Tomb answered 1/2, 2016 at 2:14 Comment(0)
F
1

Mine is for not adding @Repository on my CrudRepository interface, the tutorial I was watching didn't add it on STS and it didn't complain.

Ferdinand answered 29/4, 2016 at 9:36 Comment(0)
G
1

You should check if you have @Component, @Repository or similar added on the class

Grandioso answered 9/2, 2017 at 12:26 Comment(0)
S
1

a little late but i hope it helps to someone else.

Make sure to put the @Service on the implementation class for the service

@Service
public class ServiceNameImpl implements ServiceName {

    @Override
    public void method(ObjectType paramName) {
        //CODE
    }

}

That's how i fixed the error.

Straightforward answered 29/3, 2019 at 19:53 Comment(0)
A
1

I know this is an old question, but I haven't come across any answers that solved this problem for me so I'll provide my solution.

Note: I thought the issue may have been this, but my issue wasn't related to implementing the same interface twice. Using @Qualitier did make my issue go away, but it was a bandage and not a proper solution so I didn't settle with that.

BACKGROUND

I'm tasked with maintaining an old project that has gone through different versions of spring and only updated for separate modules, so things needed refactoring, to say the least. I had initially gotten the duplicate bean issue and tinkering with things changed the issue back and forth between OP's issue and the duplicate bean issue even though there was only one bean; navigating to the duplicate beans always went to the same class.

THE ISSUE

The issue was present on a @Repository class that was @Autowired in a @Service class which was also had the @ComponentScan annotation. I noticed that I also had a spring application-config.xml that was doing a context:component-scan on the base package, which I believe was the original approach in older versions of Spring. I was in the process of making a new branch by taking parts of an old branch and a newer branch in a support project that was used in different projects that were developed over several years and that is why there was such a mix-and-match of methodologies.

SIMPLE SOLUTION

Since the more modern approach of using @ComponentScan was already implemented I just removed the application-config.xml and the issue was solved.

Assailant answered 17/10, 2019 at 19:5 Comment(0)
S
1

The following worked for me:

  1. Find all classes implementing the service(interface) which is giving the error.
  2. Mark each of those classes with the @Service annotation, to indicate them as business logic classes.
  3. Rebuild the project.
Schleswig answered 25/3, 2020 at 9:53 Comment(0)
A
1

Fix this by adding @SpringBootTest in above the class enter image description here

Athamas answered 24/5, 2023 at 11:15 Comment(1)
You should not add images with your code, but the code itself. If you add the code as text, others can search it and can copy from it.Incorporate
L
0
eg1:
director:Settings - Editor - Inspections - Spring - Spring Core - Code - Autowiring for Bean Class 
operate:checkout 勾去掉
eg2:
1.impl class add @service
like this:
@Service
public class CityServiceImpl implements CityService{
@Autowired
private CityDao cityDao;

like this
2.dao file class add @Repository
@Repository
public interface CityDao {
Louella answered 28/9, 2017 at 10:27 Comment(0)
C
0

I've solved this problem this way. In IntelliJ all of your packages should be in a sub package which is the sub package of main/java. For example I've put all of my packages under src/main/java/com.misisol.watchStore/ and spring could find my beans then after.

Condyloid answered 24/2, 2018 at 14:13 Comment(0)
M
0

Inject Bean with @Qualifier solved the problem for me.

Montague answered 11/3, 2018 at 7:48 Comment(0)
B
0

I had similar problem. I solved it by unchecking "Process explicitly annotated beans" option (see screenshot below). This option is enabled by default on linux. Now @Service and @Configurations annotations are visible. screenshot

Bead answered 11/3, 2018 at 23:43 Comment(0)
L
0

I had this problem with only one service with constructor based dependency injection with 2019.2.4 version of IntelliJ. I found it helpful to change the name of the service (shift + f6) and then discard the changes from the git level.

Labialize answered 8/8, 2020 at 10:5 Comment(0)
S
0

For those who are using IDEA, you can simply remove those warnings that you know.

In mac, move your curse to the red wave line, press option+enter(alt+enter with Windows), you will see suggestions:

enter image description here

Try them, and you will see auto-added SuppressWarnings

Remember, option+enter always give nice solutions.

Simper answered 8/10, 2021 at 7:1 Comment(0)
D
0

Put this two annotations on top of your unit test class:

@SpringBootTest
@ExtendWith(SpringExtension.class)
class VerificationServiceTest {
    @Autowired
    private VerificationService service;
    @Test
    void matchUserBiometric() {
        service. // some method  / property
    }
}

this error appear because there is no instance of your service class on the spring container, so basically when you try to run the test a null point is going to appear, you need to initialize the spring and then an instance of your class will be available.

Dynamite answered 22/6, 2023 at 0:29 Comment(1)
Does not solve the problem for meFinagle
C
0

The error displayed refers to cases when you are trying to @Autowire a valid @Bean into a class that is not itself a valid Spring @Bean.

FIRST, make sure that the class into which you are trying to autowire the Bean, is a valid Spring Bean by annotating it with the relevant Spring Stereotype: @Component, or a specialization of it, like @Controller, @Repository, or @Service. According to the Spring Framework documentation (see here) a class annotated with the @Component or any specialization of it, are:

[...] considered as candidates for auto-detection when using annotation-based configuration and classpath scanning.

In some cases it might happen that IntelliJ Spring plugin is unable to resolve the dependency tree. If you are sure that it is the IDE that is messing things up, you can try to:

  • Delete .idea folder in the local repository, then go to File -> Invalidate Caches and reload the project
Clerihew answered 15/11, 2023 at 14:44 Comment(0)
P
0

I realize I'm late to this, but I was facing the same issue today in my service class. I just realized that I was not using the annotation @Service at the top of my class, hence it was throwing this error.

Please make sure you have specified the correct annotations for your classes in Spring boot

Peeress answered 20/1 at 17:30 Comment(0)
L
-1

I solved this issue on IntelliJ by adding annotations to my classes like

@Repository
@Service
Livvi answered 18/3, 2023 at 21:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.