Setting up a 2nd Springboot application to use a #Autowired repository #Component from App 1 caused incorrect loading and REST requests broke - spring

I have setup 2 Spring Boot applications. I am trying to #Autowire the repository from Application 1 in Application 2.
Both of these applications will be using REST to communicate back and forth. When I ran application 2 alone without the #Autowire of the repository for Application 1 I could correctly communicate with http://localhost:8082/runTestExecution via the #RestController HomeController class without an issue.
When I setup the #Autowire and #ComponentScan({"com.miw.mcb.server.repositories"}) so that I have access to the repositories of Application 1, Application 2 no longer functions correctly.
I am unable to reach the #RestController at http://localhost:8082/runTestExecution.
I also had a class which implemented CommandLineRunner which would run when I started up Spring Boot and this no longer runs either.
#Component
public class InitialRunner implements CommandLineRunner
Is this a issue because Application 1 also has a main class which loads #SpringBootApplication?
Can anyone suggest what is going wrong?
Below I have outlined my steps I took to add the jar of Application 1 and #Autowired class to Application 2
Here are the steps I took:
Setup maven to have the new library dependency and add it to the maven library mvn:install
Add Autowired bean to the HomeController class:
#RestController
public class HomeController {
#Autowired
TestSuiteRepository repo;
#RequestMapping(value = "/")
public String index() {
return "index";
}
#RequestMapping("runTestExecution")
public String runTestExecution(#RequestParam(value = "testExecutionID", required = true) String testExecutionID) {
return "Good";
}
}
Main class
#SpringBootApplication
public class AdbService {
public static void main(String[] args) {
SpringApplication.run(AdbService.class, args);
}
TestResultRepository class
package com.miw.mcb.server.repositories;
#Component
public interface TestResultRepository extends PagingAndSortingRepository<TestResult, Long> {
}
Add #Configuration and #ComponentScan, only supply the comment scan for the repositories package of the JAR file
Application 2 main class
#Configuration
#ComponentScan({"com.miw.mcb.server.repositories"})
#SpringBootApplication
public class AdbService {
public static void main(String[] args) {
SpringApplication.run(AdbService.class, args);
}
}
Application 1 Config Class
#Configuration
#ComponentScan({"com.miw.mcb.server.repositories"})
public class AppConfig {
}
Application 1 Main class
#SpringBootApplication
public class ReactAndSpringDataRestApplication {
public static void main(String[] args) {
SpringApplication.run(ReactAndSpringDataRestApplication.class, args);
}
}
Prior to adding the #ComponentScan I got the following stack trace:
2016-04-14 13:29:56 - Application startup failed
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'homeController': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: com.miw.mcb.server.repositories.TestSuiteRepository
com.miw.mcb.adbservice.HomeController.repo; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
[com.miw.mcb.server.repositories.TestSuiteRepository] found for
dependency: expected at least 1 bean which qualifies as autowire
candidate for this dependency. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
at
org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
at
org.springframework.boot.SpringApplication.refresh(SpringApplication.java:766)
at
org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:361)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:307)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1191)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1180)
at com.miw.mcb.adbservice.AdbService.main(AdbService.java:38) at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497) at
org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run(AbstractRunMojo.java:478)
at java.lang.Thread.run(Thread.java:745)

Try to use #EnableJpaRepositories instead of #ComponentScan for JpaRepositories:
#Configuration
//#ComponentScan({"com.miw.mcb.server.repositories"})
#EnableJpaRepositories("com.miw.mcb.server.repositories")
#SpringBootApplication
public class AdbService {
public static void main(String[] args) {
SpringApplication.run(AdbService.class, args);
}
}

Related

Unsatisfied dependency expressed through field on factory-bean

I am getting the following error :
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'factoryBO': Unsatisfied dependency expressed through field 'cleanupProvider': No qualifying bean of type [com.spring.factory.interfaces.impl.CleanupProvider] found for dependency [com.spring.factory.interfaces.impl.CleanupProvider]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.spring.factory.interfaces.impl.CleanupProvider] found for dependency [com.spring.factory.interfaces.impl.CleanupProvider]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:573)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:350)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:775)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.spring.factory.runner.FactoryRunner.main(FactoryRunner.java:10)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.spring.factory.interfaces.impl.CleanupProvider] found for dependency [com.spring.factory.interfaces.impl.CleanupProvider]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1398)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1051)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1018)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:570)
... 15 more
Source code :
FactoryBo.java
I added #Autowired on top od CleanupProvider class; I did it for corresponding interface as well; But it didn't work for me;
package com.spring.factory.bo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.spring.factory.interfaces.ICleanupProvider;
import com.spring.factory.interfaces.impl.CleanupProvider;
#Component
public class FactoryBO {
#Autowired
CleanupProvider cleanupProvider;
public void getFactoryProviderLogic() {
cleanupProvider.performCleanup("Algo");
}
}
CleanupProvider.java
package com.spring.factory.interfaces.impl;
import com.spring.factory.interfaces.ICleanupProvider;
import com.spring.factory.interfaces.ICleanupStrategy;
public class CleanupProvider implements ICleanupProvider {
#Override
public String performCleanup(String strate) {
System.out.println("Received Text:::"+ strate);
return strate+":"+"Received";
}
#Override
public void registerStrategy(ICleanupStrategy normalizeStrategy) {
System.out.println("NormalizationProvider:::registerStrategy::");
}
}
CleanupProviderFactory .java
So, here I want to make the existing method createInstance as a factory method;
package com.spring.factory.interfaces.impl;
import com.spring.factory.interfaces.ICleanupProvider;
import com.spring.factory.interfaces.ICleanupProviderFactory;
public class CleanupProviderFactory implements ICleanupProviderFactory {
public ICleanupProvider createInstance() {
ICleanupProvider normalizeProvider = new CleanupProvider();
normalizeProvider.registerStrategy(new CleanupStrategy());
return normalizeProvider;
}
public static ICleanupProviderFactory createFactoryInstance() {
return new CleanupProviderFactory();
}
}
ICleanupProvider.java
package com.spring.factory.interfaces;
public interface ICleanupProvider {
public String performCleanup(String algo);
public void registerStrategy(ICleanupStrategy strategy);
}
ICleanupProviderFactory.java
package com.spring.factory.interfaces;
public interface ICleanupProviderFactory {
}
package com.spring.factory.runner;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.spring.factory.bo.FactoryBO;
public class FactoryRunner {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
FactoryBO bo = context.getBean(FactoryBO.class);
bo.getFactoryProviderLogic();
context.close();
}
}
spring.xml
<context:annotation-config/>
<context:component-scan base-package="com.spring.factory.bo"></context:component-scan>
<bean id="cleanupProviderFactory"
class="com.spring.factory.interfaces.impl.CleanupProviderFactory"
factory-method="createFactoryInstance"></bean>
<bean id="cleanupProvider"
class="com.spring.factory.interfaces.ICleanupProvider"
factory-bean="cleanupProviderFactory" lazy-init="default" factory-method="createInstance"></bean>
Is there anything I missed?
You can add #Component to your CleanupProvider class:
#Component
public class CleanupProvider { ...}
Or define a method to create your been like so:
#Bean
public CleanupProvider getCleanupProvider() {
return new CleanupProvider();
}
An explanation of which annotation to use is best described here: Understanding Spring #Autowired usage
I believe you just missed providing your CleanupProvider class a #Bean annotation (like #Component, #Service, #Repository, #Controller) so that bean factory recognizes it and is able to Autowire, like this Spring documentation tells you to do so.
EDIT
Ok, so have seen your spring.xml, I assume the mistake was you were declaring the bean as ICleanupProvider class, which is the interface, whereas FactoryBO autowires the implementation (CleanupProvider).

Spring JPA not implementing/autowiring repository despite #EnableJpaRepositories annotation

I'm getting an exception when I start my application, where Spring complain about UnsatisfiedDependencyException:
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'applicationConfig': Unsatisfied dependency expressed through field 'controlRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean found for dependency [com.oak.api.finance.repository.ControlRepository]: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:569)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
My application is organized in this format:
I declared my repository interfaces, with the proper Spring JPA annotations:
#RepositoryRestResource(collectionResourceRel = "exchange", path = "exchanges")
public interface ControlRepository extends PagingAndSortingRepository<Control, Long> {
}
I annotated the EntryPoint class that contains the main method
#SpringBootApplication
#EntityScan(basePackages = {"com.oak.api.finance.model.dto"})
#EnableJpaRepositories(basePackages = {"com.oak.api.finance.repository"})
public class EntryPoint {
public static void main(String[] args) {
Logger logger = LogManager.getLogger(EntryPoint.class);
logger.info("Starting application");
ApplicationContext ctx = new AnnotationConfigApplicationContext(ApplicationConfig.class);
// SpringApplication.run(EntryPoint.class, args);
ctx.getBean(ApplicationServer.class).start();
}
I used #Autowired to inject my repository into my spring config (java based) ApplicationConfig class:
#Autowired
private ControlRepository controlRepository;
#Autowired
private CompanyRepository companyRepository;
#Autowired
private SectorRepository sectorRepository;
Essentially I want to control the dependency on Spring and limit it to a couple of packages, (the repositories, the java config, and the program entry point - EntryPoint)
I assumed that, by specifying #EnableJpaRepositories with the package where my repositories are located, spring would create a proxy for my repository and instantiate an instance of that, and that by the time I call :
ApplicationContext ctx = new AnnotationConfigApplicationContext(ApplicationConfig.class)
The repositories instances would be present in the beans poole and would be possible to autowire them into my ApplicationConfig context, and then inject them into my controller.
This is clearly not happening, and Spring is complaining about the missing Bean to autowire, but I'm not sure what am I missing.
Below a snapshot of my packages:
any ideas?
My guess is your repositories are not being scanned, so as a result beans are not getting created. Can you try removing these 2 annotations
#EntityScan(basePackages = {"com.oak.api.finance.model.dto"})
#EnableJpaRepositories(basePackages = {"com.oak.api.finance.repository"})
And keep only #SpringBootApplication. If this is not working, you might need to check the package structure (if possible paste a screenshot here)
Edit 1
replace #SpringBootApplication with
#Configuration
#EnableAutoConfiguration
#ComponentScan("com.oak")
Edit2
Use
new SpringApplicationBuilder()
.sources(SpringBootApp.class)
.web(false)
.run(args);
Or use CommandLineRunner after changing ComponentScan path to "com.oak" as mh-dev suggested

Why DataSource cannot be autowired in spring boot application?

I know that spring boot will create a dataSource Bean automatically if related configurations are set in application.properties, like:
spring.datasource.url = jdbc:mysql://192.168.10.103:3306/hms?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
spring.datasource.username=root
spring.datasource.password=test#123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
Application codeļ¼š
package com.synline.mdataserver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.apache.tomcat.jdbc.pool.DataSource;
#SpringBootApplication
public class Application implements CommandLineRunner {
#Autowired
AnnotationConfigApplicationContext context;
/*#Autowired
DataSource dataSource;*/
public static void main(String[] args) throws InterruptedException {
SpringApplication.run(Application.class, args);
}
#Override
public void run(String... args) throws Exception {
DataSource dataSource = (DataSource)context.getBean("dataSource");
System.out.println(dataSource);
while (true) {
Thread.sleep(5000);
}
}
}
If the #Autowired DataSource is commented out, the Bean information will be printed:
org.apache.tomcat.jdbc.pool.DataSource#1800a575{ConnectionPool[defaultAutoCommit=null; defaultReadOnly=null; ....}
So I think Spring Boot really created the Bean.
But if #Autowried DataSource is used, exception occurs to complain No Such Bean
Error creating bean with name 'application': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.apache.tomcat.jdbc.pool.DataSource com.synline.mdataserver.Application.dataSource; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.apache.tomcat.jdbc.pool.DataSource] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Your variable should be declared as a standard JDBC DataSource (i.e. javax.sql.DataSource), not as a particular implementation of that interface.

converting a simple maven project to a spring boot project from maven

use eclipse,I new a maven project.
After,I replace pom to the spring boot pom and create counter java file.
But when I run this application,it went error:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.yao.service.PersonInfoRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1301)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:813)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
... 31 more
I think this maybe coused by some config,but I don't know what config to.
Supplement: When I Generate the demo project from here, the same code is run normal.
This is my main class:
#ComponentScan(basePackages = { "com.yao" })
#SpringBootApplication
public class StartApplication {
public static void main(String[] args) {
SpringApplication.run(StartApplication.class, args);
}
}

A ServletContext is required to configure default servlet handling

I am trying to figure out a issue for some days but no luck. I came across this issue but not able figure out what is the problem since i am not doing any test here. java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultServletHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'defaultServletHandlerMapping' threw exception; nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1119) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1014) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
I am using spring boot
#ComponentScan
#EnableAutoConfiguration
public class Application {
.....
}
public class ApplicationWebXml extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
#Configuration
#AutoConfigureAfter
public class WebConfigurer implements ServletContextInitializer, EmbeddedServletContainerCustomizer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC);
initCachingHttpHeadersFilter(servletContext, disps);
initStaticResourcesProductionFilter(servletContext, disps);
initGzipFilter(servletContext, disps);
}
Now the problem is coming in TypeToJsonMetadataConverter bean definition in the following #Configuration classes.
#Configuration
public class EntityRestMvcConfiguration extends RepositoryRestMvcConfiguration {
#Bean
public TypeToJsonMetadataConverter typeToJsonMetadataConverter() {
return new TypeToJsonMetadataConverter(typeConfiguration(),
entityLinks());
}
#Bean
public TypeConfiguration typeConfiguration() {
return new TypeConfiguration();
}
}

Resources