I have a spring boot project, with a dependency(another spring-boot project) with an implementation like this.
#Configuration
#Lazy
#Slf4j
#RequiredArgsConstructor
public class UtilityConfiguration{
private final ProducerFactory producerFactory;
#Bean
public KafkaProducer<K, V> getProducers(){
return producerFactory.getProducers();
}
}
The getProducers method reads the kafka configuration and does
new KafkaProducer<>(producerProperties)
Context of project and problem.
The above piece of code is from an utility, which also has few other things which is of the only interest in the spring boot project, and not the kafka implementation.
However, when I start the spring boot project, this producer automatically gets initialized and fails with authentication error.
I searched in SO and found that there is an exlude filter option which can be used with component scan
Eg -
#ComponentScan(basePackages = "com.basepackage", excludeFilters = #Filter(type = FilterType.ASSIGNABLE_TYPE, classes = UtilityConfiguration.class))
But, these aren't helping.
Is there a way for me to exlcude this bean from getting created at all, THAT TOO REFERRED FROM AN UTILITY?
Any assistance would be much appreciated.
Spring version - 2.3.1.RELEASE
kafka - org.apache.kafka 2.5.0
Maybe you can use #EnableAutoConfiguration(exclude={UtilityConfiguration.class}) on top of your #SpringBootApplication annotated class as referred in the official documentation.
If the UtilityConfiguration.class is not in your classpath, you can use FQN (full qualified name) of the class.
Additionally, you can use application.properties or applycation.yml to exclude class:
spring.autoconfigure.exclude
I'm facing an issue with a dev I have to do with Spring (not spring boot).
In a class, I have to retrieve the value of a property defined on a properties files (application.properties).
So, I use the #Value annotation (normally it's easy to use), but it doesn't work in my case.
In my class, I have this code :
#Value("${value:'DefaultValue'}")
private String myValue;
with the import : import org.springframework.beans.factory.annotation.Value;
My property file contains : value=a value
But, when I want to test my application, I always receive a null value (also with the use of the default value).
I try to add deafferents annotations in my class like
#Component
...
Do you have any suggestion? I'm pretty sure I miss a config somewhere, but I don't know what.
Thanks in advance
Tigrou
Every class where you use #Value annotation MUST be a spring-managed bean. You can achieve this by adding #Component annotation but make sure that you have configured component scan #ComponentScan(basePackages = "your.package") in your java configuration, so spring knows where to search for components.
Finally, with the help of everybody here (special thanks to #M. Deinum I fixed my issue.
So, first thing done, replace the Junit dependeny (use) by a Spring test dependency.
secondly, I've updated my test to be executed with Spring with those lines :
#ExtendWith(SpringExtension.class)
#ContextConfiguration(classes = {AppConfig.class})
This was enough to retrieve the default value of the #Value field.
To retrieve the value I had to add
#PropertySource("classpath:application.properties")
in my AppConfig class
I've been attempting to make my Spring application use Spring Retry for the past few days with no luck so far. I have an XML based config so I've tried adding
<context:annotation-config/>
<aop:aspectj-autoproxy />
<bean class="org.springframework.retry.annotation.RetryConfiguration" />
along with adding the needed dependencies and setting the function I'm using #Retryable, this didn't work.
I've also added a component-scan in my XML for a newly created config file, to which I've added #Configuration and #EnableRetry. I've tried this both with an empty config file and one with a ReturnPolicy set up in it, tried both of these setups with and without Aspects instead of using #Retryable. Neither options worked.
I'm running out of sources and ideas to explore, any help would be greatly appreciated.
Thanks!
I hope you are setting and calling it correctly. The #Retryable annotation on the method to be discovered needs to be called correctly from an initialised spring context. Are you doing that( method invoked from a bean from the spring context) or called by other means - outside context?
Alternatively JUnit is best friend - try SpringJunit4ClassRunner
You should restructure your test class at least to something like:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes=MyConfig.class)
public class MyServiceTest {
#Configuration
#EnableRetry
#Import(myService.class)
public static class MyConfig {}
Couple of reference pages are here
I've managed to avoid developing any xml files so far for my Spring Boot Maven project (apart from the pom) with them all being generated on compile and I was hoping to keep this way by defining my profiles within the run commands as specified here.
By simply using #ComponentScan my main class to enable the scanning of components and tagging my DAO as #Repository I have successfully managed to autowire my UserDAOmySQLImpl class (which inherits UserDAO).
#Autowired
private UserDAO userDAO;
Then looking forward to add a second DAO for when in Live where we use a db8 implementation I need the application to figure out which UserDAO implementation needs to be used. Profiles seemed to be the answer.
After some reading, it seemed that mostly I need to add in some sort of configuration classes and external xml to manage these profiles and components, though this seems messy and I am hoping unnecessary.
I have tagged by two implementations as so:
#Repository
#Profile("dev")
public class UserDAOmySQLImpl implements UserDAO {...
-
#Repository
#Profile("dev")
public class UserDAOdb8Impl implements UserDAO {...
And then set the active profile through the Maven goals as specified here in hope that this would be a nice clean solution so I could specify the active profile within the goal for our dev and live build scripts respectively.
My current goal for testing is:
spring-boot:run -Drun.profiles=dev
However, when building I receive an error that both beans are being picked up.
*No qualifying bean of type [com.***.studyplanner.integration.UserDAO] is defined: expected single matching bean but found 2: userDAOdb8Impl,userDAOmySQLImpl*
Questions
Is the profile set in the Maven Goal the one being checked against when using the #Profile tag?
Why is Spring picking up both implementations, when if the profile isn't being set properly surely neither implementation should be selected?
Any suggestions on a nice clean way to achieve what I'm looking for?
Bonus
I would really like to set the profile within the app, as it would be easy to simply check whether an environment file exists to decide which profile to use, though I'm struggling to replicate this (found within Spring Profiles Examples
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
//Enable a "live" profile
context.getEnvironment().setActiveProfiles("live");
context.register(AppConfig.class);
context.refresh();
((ConfigurableApplicationContext) context).close();
}
in to the unusual main class in the application I am working on which I am hesitant to play around with.
public class StudyPlannerApplication {
...
public static void main(String[] args) {
SpringApplication.run(StudyPlannerApplication.class, args);
}
...
}
Any help would much appreciated.
Cheers,
Scott.
Silly me, proof reading the question I noticed that a bad copy & paste job meant that both DAO implementations had the #profile set to "Dev". After changing the db8 DAO to #Profile("live") the above works fine.
So to choose your repository based on profile is actually quite easy when using maven and spring boot.
1) Ensure your main class has the #ComponentScan annotation
#ComponentScan
public class StudyPlannerApplication {
2) Tag your components with the #Profile tags according to which profile you would like them sectected for
#Repository
#Profile("dev")
public class UserDAOdb8Impl implements UserDAO {...
-
#Repository
#Profile("live")
public class UserDAOdb8Impl implements UserDAO {...
3)
Send your profile in with your maven goal
spring-boot:run -Drun.profiles=dev
Hopefully this will help others, as I haven't seen a full example of using the autowiring profiles as I have done elsewhere on the web
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.