ChatGPT解决这个技术问题 Extra ChatGPT

intellij incorrectly saying no beans of type found for autowired repository

I have created a simple unit test but IntelliJ is incorrectly highlighting it red. marking it as an error

No beans?

https://i.stack.imgur.com/4cCFH.png

As you can see below it passes the test? So it must be Autowired?

https://i.stack.imgur.com/YFGln.png

IntelliJ sometimes gives false positive autowire errors. For example in Spring Boot applications where a lot of the configuration is hidden behind EnableAutoConfiguration. There is an open issue for that. Other cause might be incorrectly configured Spring facet. What I usually do in these situations is lowering the inspection severity so that it's less obtrusive ...
This issue happened to me because I was mixing JUnit 4/Junit 5/Jupiter, for my @Test annotation. Switching them to Jupiter solved the autowire errors.
I'm on IntelliJ 2021.2.3 and this is still happening.
Still happening IntelliJ IDEA 2022.1 (Ultimate Edition). Quite frustrating.

A
Abimbola Esuruoso

I had this same issue when creating a Spring Boot application using their @SpringBootApplication annotation. This annotation represents @Configuration, @EnableAutoConfiguration and @ComponentScan according to the spring reference.

As expected, the new annotation worked properly and my application ran smoothly but, Intellij kept complaining about unfulfilled @Autowire dependencies. As soon as I changed back to using @Configuration, @EnableAutoConfiguration and @ComponentScan separately, the errors ceased. It seems Intellij 14.0.3 (and most likely, earlier versions too) is not yet configured to recognise the @SpringBootApplication annotation.

For now, if the errors disturb you that much, then revert back to those three separate annotations. Otherwise, ignore Intellij...your dependency resolution is correctly configured, since your test passes.

Always remember...

Man is always greater than machine.


I am still getting it with 2017.2, and it is the paid for ultimate license.
For more recent versions of IntelliJ (e.g. 2017) you have to enable the Spring Data plugin and then you don't need any of the above workarounds. There's another answer below that tells you how to do that.
With IntelliJ 2018.2, using Spring Boot 2.0.5 and @SpringBootApplication I was receiving this error. I followed the advice of @Jaõs Matos by using the scanBasePackages parameter to @SpringBootApplication and specified the package/namespaces that should be scanned.
Same in 2020.3, Spring Boot 2.3.7, Kotlin 1.4.21, for @Autowired lateinit var embeddedKafka: EmbeddedKafkaBroker
Same here, version 2021.1.2 Ultimate Edition
m
mkczyk

Add Spring annotation @Repository over the repository class.

I know it should work without this annotation. But if you add this, IntelliJ will not show error.

@Repository
public interface YourRepository ...
...

If you use Spring Data with extending Repository class it will be conflict packages. Then you must indicate packages directly.

import org.springframework.data.repository.Repository;
...

@org.springframework.stereotype.Repository
public interface YourRepository extends Repository<YourClass, Long> {
    ...
}

And next you can autowired your repository without errors.

@Autowired
YourRepository yourRepository;

It probably is not a good solution (I guess you are trying to register repository twice). But work for me and don't show errors.

Maybe in the new version of IntelliJ can be fixed: https://youtrack.jetbrains.com/issue/IDEA-137023


According to this youtrack.jetbrains.com/issue/IDEA-148113 it is fixed in version 16... (holds breath)
@Component also seems to work. Looks like one just needs to force the interface / class to be scanned
You don't need to add @Repository anymore. Just on Spring Data plugin.
Three years later and it's broken again
I used /@Mapper for my mapper interface (mybatis). IDEA throw this warning. I changed it to /@Repository the warning gone.
N
Natix

My version of IntelliJ IDEA Ultimate (2016.3.4 Build 163) seems to support this. The trick is that you need to have enabled the Spring Data plugin.

https://i.stack.imgur.com/pIdbk.png


This fixed the issue for me as well -- It seems like this may be the real issue for anyone who otherwise has their code setup correctly!
Doesn't work in 2017.2.7. Plugin is enabled, but the warning is still present.
Worked for me in iJ Ultimate 2018.2.5.
Worked for intellij idea ultimate 2020
This doesn't work even after enabling the plugin
J
João Matos

Sometimes you are required to indicate where @ComponentScan should scan for components. You can do so by passing the packages as parameter of this annotation, e.g:

@ComponentScan(basePackages={"path.to.my.components","path.to.my.othercomponents"})

However, as already mentioned, @SpringBootApplication annotation replaces @ComponentScan, hence in such cases you must do the same:

@SpringBootApplication(scanBasePackages={"path.to.my.components","path.to.my.othercomponents"})

At least in my case, Intellij stopped complaining.


This is definitely the better, cleaner solution, and can confirm that this removed the warning. Thanks!
In my case I had @SpringBootApplication(scanBasePackages={"com.a.b, com.a.c"}) and although the app worked fine, intellij didn't like it. Changing to @SpringBootApplication(scanBasePackages={"com.a.b", "com.a.c"}) fixed for me!
This is by far the best solution, since it's portable between IDEs and clearly communicates developer intent.
what @GriffoGoes suggested fixed my problem, since i was ussing a multi module structure, that was my best solution
this should be the accepted answer. Clearly stating the root cause and solution.
c
cristianchiess

I always solve this problem doing de following.. Settings>Inspections>Spring Core>Code than you shift from error to warning the severity option

https://i.stack.imgur.com/9c4Xw.jpg


I went with this solution until a fix is made on Spring: youtrack.jetbrains.com/issue/IDEA-182912
In IntelliJ 2021.3 this setting has been renamed to Incorrect injection point autowiring in Spring bean components.
K
Kareem

I am using spring-boot 2.0, and intellij 2018.1.1 ultimate edition and I faced the same issue.

I solved by placing @EnableAutoConfiguration in the main application class

@SpringBootApplication
@EnableAutoConfiguration
class App{
/**/
}

This also "works" for me, but then intellij complains: Redundant declaration: @SpringBootApplication already applies @EnableAutoConfiguration ¯\_(ツ)_/¯
This is Redundant declaration: @SpringBootApplication already applies @EnableAutoConfiguration
y
yankae

Check if you missed @Service annotation in your service class, that was the case for me.


This was the case for me. make sure we have '@Service' in the service class and '@Repository' in the repository class.
w
wired00

Putting @Component or @configuration in your bean config file seems to work, ie something like:

@Configuration
public class MyApplicationContext {
    @Bean
    public DirectoryScanner scanner() {
        return new WatchServiceDirectoryScanner("/tmp/myDir");
    }
}

@Component
public class MyApplicationContext {
    @Bean
    public DirectoryScanner scanner() {
        return new WatchServiceDirectoryScanner("/tmp/myDir");
    }
}

P
Paul Roub

Configure application context and all will be ok.

https://i.stack.imgur.com/gg3BF.png


I had a service in multimodule project, adding Spring Application Context to the module in question has resolved the issue
I think in my case the problem was that I had two @SpringBootApplication annotations in one project (one for a dataloader and one for the real project). I followed your advice and defined two different application contexts explicitly as you showed it in your screenshot and then the errors were gone. Thanks!
It's useful to add the application context file in the Project setting -> Facets
v
vphilipnyc

Have you checked that you have used @Service annotation on top of your service implementation? It worked for me.

import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserServices {}

J
Julian

Use @EnableAutoConfiguration annotation with @Component at class level. It will resolve this problem.

For example:

@Component
@EnableAutoConfiguration  
public class ItemDataInitializer  {

    @Autowired
    private ItemReactiveRepository itemReactiveRepository;

    @Autowired
    private MongoOperations mongoOperations;
}

D
Devs love ZenUML

If you don't want to make any change to you code just to make your IDE happy. I have solved it by adding all components to the Spring facet.

Create a group with name "Service, Processors and Routers" or any name you like; Remove and recreate "Spring Application Context" use the group you created previously as a parent.

https://i.stack.imgur.com/NLiWU.png


R
Robert

For me the solution was to place @EnableAutoConfiguration in the Application class under the @SpringBootApplication its going to underline it because its redundant. Delete it and voila all you warnings regarding missing beans are vanished! Silly Spring...


I was so desperate I actually tried this :-) I needed to add the bean to my CoreApplication class
H
HankCa

And one last piece of important information - add the ComponentScan so that the app knows about the things it needs to wire. This is not relevant in the case of this question. However if no @autowiring is being performed at all then this is likely your solution.

@Configuration
@ComponentScan(basePackages = {
    "some_package",
})
public class someService {

This makes sense and did the trick for me. Why turn off warnings? The warnings should work as expected!
i
imal hasaranga perera

As long as your tests are passing you are good, hit alt + enter by taking the cursor over the error and inside the submenu of the first item you will find Disable Inspection select that


Thanks. By the way is there a way to see all changes made that are not default in one view in IntelliJ Settings (so you know what you have changed)?
m
malliaridis

simple you have to do 2 steps

add hibernate-core dependency change @Autowired to @Resource.

==>> change @Autowired to  @Resource

Explain your answer.
l
lmiguelvargasf

I am using this annotation to hide this error when it appears in IntelliJ v.14:

@SuppressWarnings("SpringJavaAutowiringInspection")

When autowired into a constructor it is @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
T
Tomáš Záluský

I had similar issue in Spring Boot application. The application utilizes Feign (HTTP client synthetizing requests from annotated interfaces). Having interface SomeClient annotated with @FeignClient, Feign generates runtime proxy class implementing this interface. When some Spring component tries to autowire bean of type SomeClient, Idea complains no bean of type SomeClient found since no real class actually exists in project and Idea is not taught to understand @FeignClient annotation in any way.

Solution: annotate interface SomeClient with @Component. (In our case, we don't use @FeignClient annotation on SomeClient directly, we rather use metaannotation @OurProjectFeignClient which is annotated @FeignClient and adding @Component annotation to it works as well.)


Yes, adding @Component to the interface solves the issue. But I think this is not the correct way... In my opinion this is a bug in IntelliJ IDEA or to be not so hard IntelliJ IDEA is not ready for newer Feign versions. It works without @Component in erlier feign versions (where the @FeignClient annotation was in org.springframework.cloud.netflix.feign instead of org.springframework.cloud.openfeign - maybe this is the cause of the issue?). Have you found any further details (maybe a bug ticket) for this?
No, I haven't, though my case (which didn't work without @Component) is @FeignClient from org.springframework.cloud.netflix.feign) package.
Issue at JetBrains bug tracker is here: youtrack.jetbrains.com/issue/IDEA-168155
d
davidmpaz

As most synchronisation errors between IntelliJ (IDE) and development environments.

Specially if you have automated tests or build that pass green all the way through.

Invalidate Cache and Restart solved my problem.


s
sfwn

What you need to do is add

@ComponentScan("package/include/your/annotation/component") in AppConfiguration.java.

Since I think your AppConfiguraion.java's package is deeper than your annotation component (@Service, @Component...)'s package,

such as "package/include/your/annotation/component/deeper/config".


@ComponentScan("package.include.your.annotation.component") !
K
K. Gol

I had a similar problem in my application. When I added annotations incorrect highliting dissapeared.

@ContextConfiguration(classes = {...})

only for test packages!
D
Davel_AG

in my Case, the Directory I was trying to @Autowired was not at the same level,

after setting it up at the same structure level, the error disappeared

hope it can helps some one!


A
Anton Bondarenko

IntelliJ IDEA Ultimate

Add your main class to IntelliJ Spring Application Context, for example Application.java

File -> Project Structure..

left side: Project Setting -> Modules

right side: find in your package structure Spring and add + Application.java


It is equal to U.V. answer
d
duyuanchao

just add below two annotations to your POJO.

@ComponentScan
@Configuration
public class YourClass {
    //TODO
}

Adding @ComponentScan worked for me. Thank you. I am using version 2020.3.1
U
U.V.

My solution to this issue in my spring boot application was to open the spring application context and adding the class for the missing autowired bean manually!

(access via Project Structure menu or spring tool window... edit "Spring Application Context")

So instead of SpringApplicationContext just containing my ExampleApplication spring configuration it also contains the missing Bean:

SpringApplicationContext:

ExampleApplication.java

MissingBeanClass.java

et voilà: The error message disappeared!


J
Jensen Buck

This seems to still be a bug in the latest IntelliJ and has to do with a possible caching issue?

If you add the @Repository annotation as mk321 mentioned above, save, then remove the annotation and save again, this fixes the problem.


C
Christoph Grimmer-Dietrich

Sometimes - in my case that is - the reason is a wrong import. I accidentally imported

import org.jvnet.hk2.annotations.Service

instead of

import org.springframework.stereotype.Service

by blindly accepting the first choice in Idea's suggested imports. Took me a few minutes the first time it happend :-)


s
smilyface

All you need to do to make this work is the following code:

@ComponentScan
public class PriceWatchTest{

    @Autowired
    private PriceWatchJpaRepository priceWatchJpaRepository;
...
...
}

S
Smart Coder

I just had to use @EnableAutoConfiguration to address it, however this error had no functional impact.


N
Nirbhay Rana

It can be solved by placing @EnableAutoConfiguration on spring boot application main class.