I use the following QuartzConfig configuration class to autowire spring data with quartz, this configuration class works well and fire job once I run project with no errors, but I want to fire jobs manually by the following spring controller but I got #autowire error with spring data
Quartz Job
#Service
#Transactional
public class JobOne implements Job {
#Autowired
TestrecordRepository testrecordRepository;
#Autowired
ScoreRepository scoreRepository;
public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println("Job one!");
List<Testrecord> records=testrecordRepository.findAll();
for (Testrecord t : records) {
Testrecord testrecord = new Testrecord();
testrecord.setValue_integer(t.getValue_integer());
testrecord.setId(t.getId());
RuleExecutor ruleExecutor = new RuleExecutor();
Score score = ruleExecutor.processRules(testrecord);
scoreRepository.save(score);
}
}
}
configuration class
#Configuration
public class QuartzConfig {
#Autowired
private ApplicationContext applicationContext;
#Bean
public SchedulerFactoryBean quartzSchedulerjobOne() {
SchedulerFactoryBean quartzScheduler = new SchedulerFactoryBean();
quartzScheduler.setOverwriteExistingJobs(true);
AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
jobFactory.setApplicationContext(applicationContext);
quartzScheduler.setJobFactory(jobFactory);
Trigger[] triggers = {
processjobOneTrigger().getObject()
};
quartzScheduler.setTriggers(triggers);
return quartzScheduler;
}
#Bean
public JobDetailFactoryBean processjobOne() {
JobDetailFactoryBean jobDetailFactory = new JobDetailFactoryBean();
jobDetailFactory.setJobClass(JobOne.class);
jobDetailFactory.setDurability(true);
return jobDetailFactory;
}
#Bean
public CronTriggerFactoryBean processjobOneTrigger() {
CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean();
cronTriggerFactoryBean.setJobDetail(processjobOne().getObject());
cronTriggerFactoryBean.setCronExpression("0 0/1 * * * ?");
return cronTriggerFactoryBean;
}
}
Spring controller
#RequestMapping(value = "/test", method = RequestMethod.GET)
public void test(HttpServletRequest request) throws Exception {
ApplicationContext context = new AnnotationConfigApplicationContext(
QuartzConfig.class);
Scheduler scheduler = (Scheduler)context.getBean("quartzSchedulerjobOne");
}
eclipse console
[ERROR] org.quartz.core.ErrorLogger - An error occured instantiating job to be executed. job= 'DEFAULT.processJobTwo'
org.quartz.SchedulerException: Job instantiation failed
at org.springframework.scheduling.quartz.AdaptableJobFactory.newJob(AdaptableJobFactory.java:45) ~[spring-context-support-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.quartz.core.JobRunShell.initialize(JobRunShell.java:134) ~[quartz-2.1.5.jar:na]
at org.quartz.core.QuartzSchedulerThread.run(QuartzSchedulerThread.java:387) [quartz-2.1.5.jar:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.innvo.quartz.JobTwo': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.innvo.repository.TestrecordRepository com.innvo.quartz.JobTwo.testrecordRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.innvo.repository.TestrecordRepository] 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) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBean(AbstractAutowireCapableBeanFactory.java:302) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at com.innvo.quartz.AutowiringSpringBeanJobFactory.createJobInstance(AutowiringSpringBeanJobFactory.java:22) ~[classes/:na]
at org.springframework.scheduling.quartz.AdaptableJobFactory.newJob(AdaptableJobFactory.java:41) ~[spring-context-support-4.1.6.RELEASE.jar:4.1.6.RELEASE]
... 2 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.innvo.repository.TestrecordRepository com.innvo.quartz.JobTwo.testrecordRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.innvo.repository.TestrecordRepository] 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$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
... 6 common frames omitted
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.innvo.repository.TestrecordRepository] 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.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1301) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
... 8 common frames omitted
from the error log that you posted , its clear that its looking for a bean which has not been wrapped by spring.The first bean com.innvo.quartz.JobOne.testrecordRepository where is defined? Are you sure its in the package scan? The bean name quartzSchedulerjobOne that you want to get from the application context , is anywhere defined??
Also why you try to get the Scheduler from the application context , and you dont autowire it to the controller? The scheduler has to be singleton and he will be responsible to start a new job.
Related
I'm trying to use JPA for my spring application. I have integrated the JPATransactionManager & LocalEntityManagerFactoryBean into AppConfig class. Now, when I try to call one of the method which is in DaoImpl, the AppConfig is not able to Autowire the classes. Here is my code
Test Class
public class Test {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);
BbDao personService = context.getBean(BbDao.class);
personService.getDealByDealId("0194541605021NJMAPFU");
context.close();
}
}
AppConfig
#Configuration
#EnableWebMvc
#EnableTransactionManagement
#ComponentScan(basePackages = "net.bb.spring")
public class AppConfig{
#Bean
public LocalEntityManagerFactoryBean getEntityManagerFactoryBean() {
LocalEntityManagerFactoryBean factoryBean = new LocalEntityManagerFactoryBean();
factoryBean.setPersistenceUnitName("MyPersistence");
return factoryBean;
}
#Bean
public JpaTransactionManager geJpaTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(getEntityManagerFactoryBean().getObject());
return transactionManager;
}
}
ConfirmPurchaseController
#RestController
public class ConfirmPurchaseController {
private Logger logger = Logger.getLogger(ConfirmPurchaseController.class);
#Autowired
private MyService myService;
#GetMapping("/purchase")
public ResultDto confirmpurchase(HttpServletResponse response) throws ClassNotFoundException, IOException {
// Business Logic
}
}
MyService
#Component
public interface MyService {
// Methods defined
}
MyServiceImpl
#Service
public class MyServiceImpl implements MyService, ServletContextAware {
private ServletContext servletContext;
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
public ServletContext getServletContext() {
return servletContext;
}
// Added the implemented methods of the MyService Interface
}
The exception it throws is
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myServiceImpl': Unsatisfied dependency expressed through field 'servletContext'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.servlet.ServletContext' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
and the error log is
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'confirmPurchaseController': Unsatisfied dependency expressed through field 'myService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myServiceImpl': Unsatisfied dependency expressed through field 'servletContext'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.servlet.ServletContext' available: 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:588)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
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:761)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:84)
at net.bb.spring.controller.Test.main(Test.java:14)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myServiceImpl': Unsatisfied dependency expressed through field 'servletContext'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.servlet.ServletContext' available: 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:588)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
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:202)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
... 14 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.servlet.ServletContext' available: 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.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1493)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
... 27 more
Any ideas would be very helpful for me.
P.S : Im using configuration as annotations, no XML
It is not an answer, however I cannot add a comment yet.
Did you try to autowire a ServletContext via setter method?
- remove #Autowired from property
- remove one of your setters for context (unnecessary duplication)
- mark a setter as #Autowired
Moreover remove #Component annotation from MyService, it is unnecessary if you are using #Service annotation in its implementation.
As per Apache Tomcat documentation, a ServletContext
Defines a set of methods that a servlet uses to communicate with its
servlet container.
There is one context per "web application" per Java Virtual Machine.
(A "web application" is a collection of servlets and content installed
under a specific subset of the server's URL namespace such as /catalog
and possibly installed via a .war file.)
Which means that a ServletContext is only valid within a Servlet Container like Apache Tomcat. But as I can see, you are trying to run a normal Java application by creating beans in a main method, which makes the existence of ServletContext invalid.
So what you have to do is:
STEP 1: Build your AppConfig and override required methods.
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = {"net.bb.spring"})
public class AppConfig extends WebMvcConfigurerAdapter {
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/");
}
//....
}
STEP 2: Create WebInitializer to initialize Dispatcher Servlet
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] {AppConfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
STEP 3: Create your Service layer to autowire ServletContext
#Service
public class MyServiceImpl implements MyService {
private ServletContext servletContext;
#Autowire
public MyServiceImpl(ServletContext servletContext) {
this.servletContext = servletContext;
}
public ServletContext getServletContext() {
return servletContext;
}
//...
}
STEP 4: Build your application to a WAR file
STEP 5: Deploy your WAR file to webapp folder of Tomcat (If you are using Tomcat)
STEP 6: Start Tomcat
Here is what you need to change:
1) You don't need to annotate the interface with #Component, annotation is required only on the implementation class
MyService
public interface MyService {
// Methods defined
}
2) Use constructor injection to obtain an instance of ServeletContext.
#Service
public class MyServiceImpl implements MyService, ServletContextAware {
private ServletContext servletContext;
#Autowire
public MyServiceImpl(ServletContext servletContext) {
this.servletContext = servletContext;
}
//TODO: other methods goes here...
}
pay attention that ServletContext is not a Spring bean and it can, therefore, not be injected unless you implement ServletContextAware. keep your implementation class implements ServletContextAware
i have below code.
Interface
#Component
public interface Service {
public String getConfig();
}
2 implementation
#Service("UserService")
public class userService implements Service{
#Override
public String getConfig() {
// logic goes here
return "result";
}
}
customer implementation
#Service("CustomerService")
public class userService implements Service{
#Override
public String getConfig() {
// logic goes here
return "result";
}
}
I have a configuration class where i need the bean dynamically
#Configuration
public class MyConfig {
#Autowired
ApplicationContext context;
#Bean
public Service getConfigBean(final String configName) {
Service service = (Service) context.getBean(configName);
return service;
}
}
from my controller/any other class i just want get the bean object
#RestController
#RequestMapping("/user")
#Scope(value = WebApplicationContext.SCOPE_REQUEST)
public class UserController {
#Autowired
MyConfig myConfig;
#Autowired
Service service;
#RequestMapping(produces = MediaType.TEXT_HTML , method = RequestMethod.GET)
public String getInitiate()
{
service = stateConversationConfig.getConfigBean("UserService"); // will get this String dynamically or based on logic
System.out.println("service object : "+service);
return "ok";
}
}
But when i run my application on tomcat, its failed to deploy with following exception
SEVERE: Application startup failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'getConfigBean' defined in class path resource [xxx/xxx/xxx/xxxxx.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [java.lang.String]: : No qualifying bean of type [java.lang.String] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:464)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1119)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1014)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
at xx.xxx.xxxx.xxx.xxx.main(Application.java:36)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] 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)
Am I doing something wrong.?
Beans are objects managed by Spring IoC container. When application context is created, beans are constructed, but Spring cannot create your configBean as it does not know what value should be passed to configName.
If you want dynamic services, I suggest that you create 2 separate beans (userServices and customerService) and a normal function (not with #Bean) getConfigBean(String configName).
Hello guys I am having some troubles while working with spring-JPA and testing the code in main method I would really appreciate it if anybody can tell me what's that I am missing here or can direct me towards a good complete tutorial .
Here is my configuration class
#Configuration
#EnableJpaRepositories
public class Config {
#Bean
public InsertExample insertExample() {
return new InsertExample() ;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean emfb = new LocalContainerEntityManagerFactoryBean() ;
emfb.setDataSource(dataSource());
emfb.setPackagesToScan("com.solveit.insert");
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter() ;
emfb.setJpaVendorAdapter(vendorAdapter);
return emfb ;
}
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/datastore");
dataSource.setUsername("root");
dataSource.setPassword("nikolis");
return dataSource ;
}
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
JpaTransactionManager transactionManager = new JpaTransactionManager() ;
transactionManager.setEntityManagerFactory(emf);
return transactionManager ;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor() ;
}
#Bean
public Properties hibernateProperties() {
Properties hibernateProps = new Properties();
hibernateProps.setProperty("hibernate.hbm2ddl.auto", "create");
return hibernateProps;
}
}
This is my repository
public interface ExampleRepository extends CrudRepository<ExampleModel, Long> {
List<ExampleModel> findByLastName(String lastName);
}
This is the model
#Entity
public class ExampleModel {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private long id;
#Column
private String klass ;
#ElementCollection
private List<Double> features ;
public ExampleModel() {
}
public ExampleModel(String klass, ArrayList<Double> features) {
this.klass=klass ;
this.features=features ;
}
public String getKlass() {
return klass;
}
public void setKlass(String klass) {
this.klass = klass;
}
public ArrayList<Double> getFeatures() {
return (ArrayList<Double>) features;
}
public void setFeatures(ArrayList<Double> features) {
this.features = features;
}
}
And this is my test code :
#Configuration
#Import({ Config.class })
public class InsertExample implements CommandLineRunner {
#Autowired
ExampleRepository repository ;
public static void main(String args[]) throws FileNotFoundException{
SpringApplication.run(InsertExample.class);
}
public void run(String... arg0) throws Exception {
PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
ArrayList<Double> asdf = new ArrayList<Double>();
asdf.add(23.123) ;
asdf.add(23.123) ;
asdf.add(23.123) ;
asdf.add(23.123) ;
ExampleModel example = new ExampleModel("first", asdf) ;
repository.save(example) ;
}
}
And this is the Exception that I get
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'insertExample': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.solveit.insert.ExampleRepository com.solveit.insert.InsertExample.repository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.solveit.insert.ExampleRepository] 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:1210)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
at com.solveit.insert.InsertExample.main(InsertExample.java:33)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.solveit.insert.ExampleRepository com.solveit.insert.InsertExample.repository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.solveit.insert.ExampleRepository] 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$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 15 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.solveit.insert.ExampleRepository] 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.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.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 17 more
You need to use this annotation with the package path:
#EnableJpaRepositories("com.solveit.insert.hereyourrepositories")
UPD:
At least, you have to do this after changing path in #EnableJpaRepositories:
1.Spring boot config required this structure. Because spring didn't start scanning of the beans which needs to be initialized like JPA.
http://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-structuring-your-code.html
2.You can use only JpaTransactionManager.
PlatformTransactionManager is interface, but JPATransactionManager is implementation of interface that understands JPA.
You should read the chapter Transaction Management from the Spring reference to better understand this topic.
http://docs.spring.io/spring/docs/3.0.4.RELEASE/spring-framework-reference/html/transaction.html
hibernateProps.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect");
It needs for working with JPA.
Other changes not important.
Having this class, I am havin to perform some tests with the library junit 4.4. without success
public class GeolocationServiceTest extends AbstractAnnotationAwareTransactionalTests {
private static final String GEOJSON_FILE = "geojson_demo.geojson";
private static final String GEOJSON_FILE2 = "geojson_ecat.geojson";
private static final String ADDRESS = "rue commerce+PARIS";
private static final String ADDRESS2 = "Gravilliers 12, Paris";
private static final String[] CONFIG_LOCATIONS = new String[] {
"classpath:com/devices/testServiceContext.xml",
"classpath:com/devices/testApplicationContext.xml", "classpath:com/devices/testDatabaseMessageSource.xml", "classpath:com/devices/propertyeditorsContext.xml" };
#Autowired
private CompanyDao companyDao;
#Autowired
private GeolocationService geolocationService;
...
}
I got this strange error saying that is not posible the injection of a bean, but this bean exists in the file testServiceContext.xml so i don't understand it at all.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.devices.services.GeolocationServiceTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.devices.services.geolocation.GeolocationService com.devices.services.GeolocationServiceTest.geolocationService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.devices.services.geolocation.GeolocationService] 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:289)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1146)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:376)
at org.springframework.test.AbstractDependencyInjectionSpringContextTests.injectDependencies(AbstractDependencyInjectionSpringContextTests.java:210)
at org.springframework.test.AbstractDependencyInjectionSpringContextTests.prepareTestInstance(AbstractDependencyInjectionSpringContextTests.java:184)
at org.springframework.test.AbstractSingleSpringContextTests.setUp(AbstractSingleSpringContextTests.java:103)
at junit.framework.TestCase.runBare(TestCase.java:139)
at org.springframework.test.ConditionalTestCase.runBare(ConditionalTestCase.java:79)
at org.springframework.test.annotation.AbstractAnnotationAwareTransactionalTests.access$001(AbstractAnnotationAwareTransactionalTests.java:74)
at org.springframework.test.annotation.AbstractAnnotationAwareTransactionalTests$1.run(AbstractAnnotationAwareTransactionalTests.java:179)
at org.springframework.test.annotation.AbstractAnnotationAwareTransactionalTests.runTest(AbstractAnnotationAwareTransactionalTests.java:287)
at org.springframework.test.annotation.AbstractAnnotationAwareTransactionalTests.runTestTimed(AbstractAnnotationAwareTransactionalTests.java:258)
at org.springframework.test.annotation.AbstractAnnotationAwareTransactionalTests.runBare(AbstractAnnotationAwareTransactionalTests.java:176)
at junit.framework.TestResult$1.protect(TestResult.java:122)
at junit.framework.TestResult.runProtected(TestResult.java:142)
at junit.framework.TestResult.run(TestResult.java:125)
at junit.framework.TestCase.run(TestCase.java:129)
at junit.framework.TestSuite.runTest(TestSuite.java:255)
at junit.framework.TestSuite.run(TestSuite.java:250)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:84)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.devices.services.geolocation.GeolocationService com.devices.services.GeolocationServiceTest.geolocationService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.devices.services.geolocation.GeolocationService] 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$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:517)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:286)
... 25 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.devices.services.geolocation.GeolocationService] 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.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:988)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:858)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:770)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:489)
... 27 more
here you can see the file testServiceContext.xml:
<!-- Scan for services -->
<context:component-scan base-package="com.devices.services.impl" />
<context:component-scan base-package="com.devices.services.geolocation" />
and the class seems to be well declared
package com.devices.services.geolocation
#Service(value = "geolocationService")
public interface GeolocationService {
....
}
This exception you will receive in below scenario:
#Service(value = "geolocationService")
public interface GeolocationService {
....
}
Now you have created the implementation of above interface
public class GeolocationServiceImpl implements GeolocationService {
..........
}
Now if you try to inject GeolocationService through #Autowired, will receive exception :
No qualifying bean of type [com.devices.services.geolocation.GeolocationService] found for dependency
Solution for it:
1) Either put #Component annotation on GeolocationServiceImpl as below:
#Component
public class GeolocationServiceImpl implements GeolocationService {
..........
}
2) Define it in spring-context.xml as:-
<bean id="geolocationService" class="com.devices.services.geolocation.GeolocationServiceImpl" />
In-short you need to make the Spring ApplicationContext aware of implementation of your interface.
Application-Context is correctly setup!
Heres my class scenario
public interface IManager
{
public void doStuff();
}
#Component
public abstract class ManagerAction implements IManager
{
#Async
#Override
public void doStuff()
{
//doing stuff
}
public abstract manageWorker();
}
#Component
public class Working extends ManagerAction
{
#Override
public manageWorker()
{
//some busy code
}
}
#Component
public class NotWorking extends ManagerAction
{
#Override
public manageWorker()
{
//some busy code
}
}
#Service
public class BusinessWorker
{
#Autowire
private IManager manager_;
public void preformTasks()
{
manager_.doStuff();
}
}
Heres my error
ERROR [main] (ContextLoader.java:307) - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'BusinessWorker': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.B
eanCreationException: Could not autowire field: private com.background.IManager com.background.BusinessWorker.manager_; nested exception is org.springframework.beans.
factory.NoSuchBeanDefinitionException: No matching bean of type [com.background.IManager] 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)}
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.background.IManager com.background.BusinessWorker.manager_;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.background.IManager] 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$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:506)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
... 28 more
Application-Context
<mvc:annotation-driven />
<task:annotation-driven />
<context:annotation-config />
<context:component-scan base-package="com.background" />
The error message says it all: you try to autowire an instance of IManager, but two different Spring components implement this interface, so Spring doesn't know which one to autowire. You need to use the #Qualifier annotation to specify which one you want Spring to autowire.