I am creating a Maven artifact with following classes and configuration in custom Spring Starter project:
#ConfigurationProperties(prefix = "commons.time.formats")
#Getter
#Setter
public class TimeFormatConf {
... fields
}
#Component
#Configuration
#AllArgsConstructor
#EnableConfigurationProperties(TimeFormatConf.class)
#AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
public class DateTimeConfigurer {
private final TimeFormatConf timeFormatConf;
#EventListener(ApplicationReadyEvent.class)
public void configureTimeFormat() {
TimeZone.setDefault(TimeZone.getTimeZone(timeFormatConf.getDynamicZone()));
System.setProperty("user.timezone", timeFormatConf.getDynamicZone());
}
}
And spring.factories (src/main/resources/META-INF/spring.factories):
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
[package].DateTimeConfigurer,\
...
When I try to autowire a TimeFormatConf class my spring application crashes at start up as it cannot find a bean of TimeFormatConf class:
Parameter 0 of constructor in com.some.package.b.Class required a bean
of type 'com.some.package.a.TimeFormatConf' that could not be found.
The artifact is present with correct configuration on classpath. So it has to do something with either declaration or configuration of Spring.
I have also tried adding #Component on properties class and #ComponentScan on configuration class does not have any effect.
Reverting to Spring Boot 2.7.7 on both projects fixed the problem. So it seems to be a bug or at least lack of documentation. I have opened an issue to follow this up with spring team: https://github.com/spring-projects/spring-boot/issues/33720
There seems to be a change in the way configurations beans are detected by Spring since version 2.7, it seems to be covered in this migration guide
Basically, instead of providing configuration in META-INF/spring.factories, you would do so in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
I and my friend were discussed about #ComponentScan and #Import. Which one is better?
We have 2 different ideas.
#ComponentScan: Easy to use, import all beans from the component
scan.
#Import: You need to know what component you want to use, no need to scan all.
How about your idea? Which one is better for you to use?
Thanks!
#Import is used to import Java configuration classes marked with #Configuration/#Component typically. So if you have a bean inside this component, Spring will load it into Application Context. You can just put the name of the component or class and Spring will pull it up for you.
However, by using #ComponentScan, you tell the application which packages to scan for java classes are annotated with #Configuration/#Component (or any of #Component's sub-annotations like #Service or #Repository etc) and load all of them up in Application Context so they can be autowired when required. If there are inner instances that need to be populated, Spring will take care of it.
You can read more about #Import and #ComponentScan on their respective doc pages.
This page explains pretty well the difference.
#ComponentScan scans and searches for any beans inside packages/classes specified under basePackageClasses or basePackages options, whichever is configured.
This option also allows you to filter some classes that you do not want to be included in search.
#Import is like clubbing one java configuration into another.
eg:
#Configuration
#ComponentScan(basePackages="com.stackoverflow")
public class Dbconfig {
#Bean
public Datasource dSource(){
return new Datasource()
}
}
#Configuration
#Import(Dbconfig.class)
#ComponentScan(basePackages="org.hellospring")
public class AppConfig {
...// beans
}
So here, if we check AppConfig class,
it will include all beans registered in Dbconfig configuration class including inside of package com.stackoverflow
+
It will include all beans inside AppConfig class and beans under package org.hellospring
We have an application that relies on Spring Boot 2.0. We are in the process of migrating it to JDK11 from JDK8. This also enabled us to update Spring Boot from 2.0 to 2.1. After reading through the changelog, it appeared there was any major change that needed for us.
Now the problem lies in where some test classes are annotated with both #SpringBootTest and #DataJpaTest. As per this and as well as the documentation, we are not supposed to use both together and instead we changed #DataJpaTest to #AutoConfigureTestDatabase. Here is how the code is:
#RunWith(SpringRunner.class)
#SpringBootTest(classes = {A.class, B.class}, properties = {
"x=xxx",
"y=yyy"
})
#AutoConfigureTestDatabase // Used to be #DataJpaTest
#EnableJpaRepositories("com.test")
#EntityScan("com.test")
public class Test {
#TestConfiguration
public static class TestConfig {
// Some beans returning
}
// Tests
}
Now, we end up with the following error:
NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
So as per this answer, we did something like this:
#EnableJpaRepositories(basePackages="com.test", entityManagerFactoryRef="entityManagerFactory")
Even after this we still end up with the same error. Is this the right way to remove #DataJpaTest? Or do we need to remove #SpringBootTest and do something else? Any sort of guidance is much appreciated.
The testclass is annotated with #DataJpaTest and #ContextConfiguration
#RunWith(SpringRunner.class)
#DataJpaTest
#ContextConfiguration(locations = { "classpath:test-context.xml" })
public abstract class AbstractTestCase {
protected static final Logger LOG = LoggerFactory.getLogger(AbstractTestCase.class);
}
We defined a test-context.xml. This is because the testmodule is isolated from all other modules (multi maven module project). In the test-context.xml we defined the component-scan for the base-package.
<context:component-scan base-package="de.example.base.package" />
I have created a simple unit test but IntelliJ is incorrectly highlighting it red. marking it as an error
No beans?
As you can see below it passes the test? So it must be Autowired?
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.
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
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.
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.
I always solve this problem doing de following..
Settings>Inspections>Spring Core>Code than you shift from error to warning the severity option
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{
/**/
}
Check if you missed #Service annotation in your service class, that was the case for me.
Configure application context and all will be ok.
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 {}
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");
}
}
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;
}
simple you have to do 2 steps
add hibernate-core dependency
change #Autowired to #Resource.
==>> change #Autowired to #Resource
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.
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
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...
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 {
I am using this annotation to hide this error when it appears in IntelliJ v.14:
#SuppressWarnings("SpringJavaAutowiringInspection")
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.)
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!
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.
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".
I had a similar problem in my application.
When I added annotations incorrect highliting dissapeared.
#ContextConfiguration(classes = {...})
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
just add below two annotations to your POJO.
#ComponentScan
#Configuration
public class YourClass {
//TODO
}
#Autowired(required = false)
will shut intellij up
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!
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.
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 :-)
All you need to do to make this work is the following code:
#ComponentScan
public class PriceWatchTest{
#Autowired
private PriceWatchJpaRepository priceWatchJpaRepository;
...
...
}
I just had to use #EnableAutoConfiguration to address it, however this error had no functional impact.
I'm working on updating an older Spring MVC application from xml based to annotation based configuration. I'm not sure how to add "name-generator" to the #ComponentScan annotation.
Here's what I have:
#Configuration
#EnableAsync
#EnableScheduling
#EnableAspectJAutoProxy
#ComponentScan({"com.styxrbad", "com.styxrbad.common"})
#Import({DatabaseConfiguration.class, WebMvcConfiguration.class})
public class SpringConfiguration
{
}
I need to include my implemented BeanNameGenerator to replace the "name-generator" field from the xml within the annotations. I'm rather new to Spring and I do not know the syntax nor can I find any examples in my research. How can I do this?
#ComponentScan has a property nameGenerator.
Is it enough for you ?
UPDATE:
#ComponentScan(value = {"com.styxrbad", "com.styxrbad.common"}, nameGenerator = MyBeanNameGenerator.class)