Failed to load ApplicationContext in JUnit with JNDI datasource - spring

I have some troubles testing my application, whereas it works well in normal execution.
I think it comes from JNDI resources which are not found, but I don't understand why and how to fix it.
When I start my Junit test, I got this error:
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
at ...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'DAOImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource com.sample.DAOImpl.myDatasource; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.sql.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), #org.springframework.beans.factory.annotation.Qualifier(value=myDatasource)}
Related cause: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myDatasource' defined in URL [file:src/test/resources/spring/test-dao-config.xml]: Invocation of init method failed; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288)
at ...
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource com.sample.DAOImpl.myDatasource; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.sql.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), #org.springframework.beans.factory.annotation.Qualifier(value=myDatasource)}
at ...
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.sql.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), #org.springframework.beans.factory.annotation.Qualifier(value=myDatasource)}
at ..
Here is my configuration:
Context.xml
<Resource name="jdbc/myDatasource" auth="Container" type="javax.sql.DataSource"
driverClassName="oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:#database:99999:instance"
username="user"
password="password"
validationQuery="select 1 from dual"
testOnBorrow ="true"
maxActive="5"
maxIdle="1"
maxWait="-1" />
test-dao-config.xml
<bean id="myDatasource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/myDatasource" />
</bean>
DaoImpl
#Repository
public class DacsDAOImpl implements DacsDAO
{
private final static Logger LOGGER = LoggerFactory.getLogger(DAOImpl.class);
#Autowired
#Qualifier("myDatasource")
private DataSource myDatasource;
....
}
And my tests
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "file:src/test/resources/spring/test-dao-config.xml" })
public class MyDAOImplTest
{
private MyDAO dao;
#BeforeClass
public static void initJndi() throws IllegalStateException, NamingException
{
//some test, but doesn't work
// SimpleNamingContextBuilder builder = SimpleNamingContextBuilder.emptyActivatedContextBuilder();
// builder.bind("java:comp/env/jdbc/myDatasource", "myDatasource");
// builder.activate();
}
#Before
public void setUp() throws IllegalStateException, NamingException
{
dao = new MyDAOImpl();
}
#Test
public void testTotalUser()
{
int result = dao.getTotalUser();
Assert.assertEquals(0, result);
}
}
Thanks

You are running in a test case so everything in your Context.xml isn't available as that is only available on tomcat. Why do you need a jndi lookup in your test case anyway? If you want to test your dao use an in-memory database like hsql, h2 or derby and use that instead. Spring has some nice tags to make it easy for you.
<jdbc:embedded-database id="myDataSource" type="H2">
// Add some init scripts here.
</jdbc:embedded-database>
If you really need to do a JNDI lookup you are almost there in your test case. However you have to register a DataSource not a String. So you still will need to construct some (in-memory) datasource and bind that to the mock jndi location
#BeforeClass
public static void initJndi() throws IllegalStateException, NamingException
{
//some test, but doesn't work
// Construct in-memory database
SimpleNamingContextBuilder builder = SimpleNamingContextBuilder.emptyActivatedContextBuilder();
builder.bind("java:comp/env/jdbc/myDatasource", myDatasource); //Actual datasource not a String!
builder.activate();
}
And finally your test is also flawed, you are loading your context but aren't doing anything with it. You are constructing a MyDAOImpl in your #Before method. Why even bother loading the context as you are doing nothing with.

Related

How to autowire a service and a repository together

I have to fix the following error. Anyone can help
SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'searchController': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire method: public void
com.website.dev.controller.SearchController.setRecordingService(com.website.dev.service.RecordingService);
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type [com.website.dev.service.RecordingService]
found for dependency: expected at least 1 bean which qualifies as
autowire candidate for this dependency. Dependency annotations: {}
#Controller
public class SearchController {
private RecordingService recordingService;
#Autowired
public void setRecordingService(RecordingService recordingService) {
this.recordingService = recordingService;
}
#RequestMapping("/search")
public String showSearch(){
return "search";
}
}
#Service("recordingService")
public interface RecordingService {
//methods
}
public class RecordingServiceImpl implements RecordingService {
#Autowired
private RecordingRepository recordingRepository;
//methods that use recordingRepository
}
public interface RecordingRepository {
}
#Repository
public class RecordingJpaRepository implements RecordingRepository {
#PersistenceContext
private EntityManager entityManager;
//methods that use entityManager
}
service-context.xml
<context:annotation-config></context:annotation-config>
<context:component-scan
base-package="com.website.dev.service">
</context:component-scan>
</beans>
website-servlet.xml
<context:component-scan
base-package="com.website.dev.controller"> // searchcontroller is in this package
</context:component-scan>
web.xml
<context:component-scan
base-package="com.enepath.dev.controller">
</context:component-scan>
EDIT
If I autowire RecordingServiceImpl I get the following
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'recordingServiceImpl': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private com.website.dev.repository.RecordingRepository
com.website.dev.service.RecordingServiceImpl.recordingRepository;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
[com.website.dev.repository.RecordingRepository] 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)}
I added the following configuration in service-context.xml and this solved my issue
<context:annotation-config></context:annotation-config>
<context:component-scan
base-package="com.website.dev.service">
</context:component-scan>
<context:component-scan
base-package="com.website.dev.repository">
</context:component-scan>
<context:component-scan
base-package="com.website.dev.repository.jpa">
</context:component-scan>
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.website.dev.service.RecordingService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
If we look above exception, we will find that spring container is unable to create or instantiate the bean of type com.website.dev.service.RecordingService.
It is because POJO class is not managed by spring container.
#Autowire annotation will work only those objects which are managed by spring (ie created by the spring container).
you should annotate the RecordingServiceImpl class as Service
#Service
public class RecordingServiceImpl implements RecordingService
and remove #Service("recordingService") from
public interface RecordingService {
//methods
}
RecordingServiceImpl would be managed by Spring container and spring would be able to create the bean.

Instantiation of bean failed : Specified class is an interface

I am facing an issue while creating a bean for dependency injection. Here is the scenario.
I am dealing with MongoDB repository, I have also created a class which uses it. I am trying to instantiate bean instance of both.
MongoDB reporsitory:
#Repository
public interface ProductGlobalTrendRepository extends MongoRepository<ProductGlobalTrend,String>{
public ProductGlobalTrend findByPid(#Param("pId") String pId);
}
The class which is using it:
#Service
#Scope("singleton")
public class ProductTrendService {
#Autowired
#Qualifier("productGlobalTrendRepo")
ProductGlobalTrendRepository productGlobalTrendRepo;
public ProductTrendService() {
super();
}
public void setProductGlobalTrendRepo(
ProductGlobalTrendRepository productGlobalTrendRepo) {
this.productGlobalTrendRepo = productGlobalTrendRepo;
}
public ProductTrendService(ProductGlobalTrendRepository productGlobalTrendRepo) {
super();
this.productGlobalTrendRepo = productGlobalTrendRepo;
}
}
The spring's bean config xml has these entries:
<bean id="productTrendService" class="com.api.services.ProductTrendService"> </bean>
<bean id="productGlobalTrendRepo" class="com.mongodb.repository.ProductGlobalTrendRepository"> </bean>
Following is the error I am getting:
19428 [localhost-startStop-1] WARN
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
- Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'productTrendService': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: com.mongodb.repository.ProductGlobalTrendRepository
com.api.services.ProductTrendService.productGlobalTrendRepo; nested
exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'productGlobalTrendRepo' defined in
class path resource [com/vstore/conf/spring-security.xml]:
Instantiation of bean failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [com.mongodb.repository.ProductGlobalTrendRepository]:
Specified class is an interface
It complains that repository is a interface class.
Can somebody please suggest a fix/workaround for this bean dependency injection ?
The problem is with the following information in your context file
<bean id="productGlobalTrendRepo"
class="com.mongodb.repository.ProductGlobalTrendRepository">
</bean>
You should create a class com.mongodb.repository.ProductGlobalTrendRepositoryImpl which implements com.mongodb.repository.ProductGlobalTrendRepository and provides implementation of its methods.
then change your bean declaration info as
<bean id="productGlobalTrendRepo"
class="com.mongodb.repository.ProductGlobalTrendRepositoryImpl">
</bean>
Behind the scene the object is created which is not possible with the interface.

Spring-boot with Liquibase Overloading Property

I am using Spring boot and Liquibase.
Using this url as guidelines
http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/
In pom.xml, the below entry is present so that spring boot knows about liquibase.
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
</dependency>
and put the changelog file in resources folder.
db.changelog-master.xml
Now Spring boot first tring to find db.changelog-master.yaml in classpath and throwing the exception like this.
Cannot find changelog location: class path resource [db/changelog/db.changelog-master.yaml
To Fix the Issue, I have added the bean like below in my class and tried to set changeLog proprty.
#Configuration
#ComponentScan
#EnableAutoConfiguration
public class SampleDataJpaApplication {
#Autowired
LiquibaseProperties properties;
#Autowired
private DataSource dataSource;
#Bean
public SpringLiquibase liquibase() {
SpringLiquibase liquibase = new SpringLiquibase();
properties.setChangeLog("classpath:/db/changelog/db.changelog-master.xml");
liquibase.setChangeLog(this.properties.getChangeLog());
liquibase.setContexts(this.properties.getContexts());
liquibase.setDataSource(this.dataSource);
liquibase.setDefaultSchema(this.properties.getDefaultSchema());
liquibase.setDropFirst(this.properties.isDropFirst());
liquibase.setShouldRun(this.properties.isEnabled());
return liquibase;
}
public static void main(String[] args) throws Exception {
Logger logger = LoggerFactory.getLogger("SampleDataJpaApplication");
SpringApplication springApplication = new SpringApplication();
springApplication.run(SampleDataJpaApplication.class, args);
}
}
but it is failing with the message.
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'sampleDataJpaApplication': Injection of
autowired dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field:
org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties
sample.data.jpa.SampleDataJpaApplication.properties; nested exception
is org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
[org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties]
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:
org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties
sample.data.jpa.SampleDataJpaApplication.properties; nested exception
is org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
[org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties]
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)}
Please provide the inputs here, why i am getting this exception or Is there any any other available way to override the same class so that i can change the changeLog property of liquibase properties.
I'm not entirely sure what the exact runtime path to your change log is, but why don't you just use the "liquibase.*" properties in application.properties? You should be able to leave out the Liquibase #Bean and let Boot do it for you.
If you prefer to add you own Liquibase #Bean then take the hint and make sure you define a LiquibaseProperties bean as well (e.g. by declaring #EnableConfigurationProperties(LiquibaseProperties.class)).

Spring and Spring Data JPA are not working in conjunction

I am using Spring Data JPA (1.3.0.RELEASE) with Spring (3.2.2.RELEASE ) in one project and facing a weird problem. I am using xml based configuration as mentioned below.
<context:annotation-config/>
<context:component-scan base-package="x.y.z.services"/>
Using this configuration to scan the classes decorated with #Component, #Service and #Named annotations.
<jpa:repositories base-package="x.y.z.repo"/>
Using this configuration to scan all interfaces extending JpaRepository. These interfaces are injected in Service classes in the following way.
#Service
public class UserServiceImpl implements UserService {
private UserRepository userRepository;
#Inject
public void setUserRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}
#Override
public List<User> listUsers() {
return userRepository.findAll();
}
}
This configuration works as expected without any issue. But when I add the following configuration I get the BeanCreationException for UserRepository.
<bean id="securityRealm" class="x.y.z.Realm">
<property name="userService">
<bean class="x.y.z.services.UserServiceImpl"/>
</property>
</bean>
And, here is the Java code for Realm and UserRepository.
public class Realm extends AuthorizingRealm implements IRealm {
private UserService userService;
#Inject
public void setUserService(UserService userService) {
this.userService = userService;
}
#Override
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken token) throws AuthenticationException {
return null;
}
}
public interface UserRepository extends JpaRepository<User, String> {
}
As per above configuration, Spring is able to create the bean for userService but not able to create the UserRepository bean.
I can get this error away by scanning x.y.z.Realm and decorating it with #Service annotation. But it will be a very big constraint and design issue to my application.
AFAICT, Spring is not able to create the bean for UserRepository as it's implementation class is not available and has to be provided by jpa:repositories configuration. I can see that Spring and Spring Data JPA are not working in conjunction.
Can somebody please help me to solve this problem. Below is stacktrace of the exeception.
2013-04-30 21:44:04.745:INFO:/web:Initializing Spring root WebApplicationContext
2013-04-30 21:44:07,009 [ERROR] [main] [org.springframework.web.context.ContextLoader] - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shiroFilter' defined in class path resource [META-INF/Test-web/security-config.xml]: Cannot resolve reference to bean 'securityManager' while setting bean property 'securityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testShiroRealm': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: x.y.z.core.service.UserService x.y.z.core.security.testShiroRealm.userService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void x.y.z.core.service.internal.UserServiceImpl.setUserRepository(x.y.z.repo.UserRepository); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [x.y.z.repo.UserRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:329)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:107)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1393)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1134)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:522)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
at org.springframework.context.support.AbstractApplicationContext.registerBeantesttProcessors(AbstractApplicationContext.java:753)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.eclipse.jetty.server.handler.ContextHandler.callContextInitialized(ContextHandler.java:764)
at org.eclipse.jetty.servlet.ServletContextHandler.callContextInitialized(ServletContextHandler.java:406)
at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:756)
at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:242)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1221)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:699)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:454)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)
at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:90)
at org.eclipse.jetty.server.Server.doStart(Server.java:263)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)
at runjettyrun.Bootstrap.main(Bootstrap.java:80)
... 34 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void x.y.z.core.service.UserServiceImpl.setUserRepository(x.y.z.repo.UserRepository); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [x.y.z.repo.UserRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:601)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
... 45 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [x.y.z.repo.UserRepository] 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:986)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:856)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:558)
... 47 more
This was the bug in Spring Data JPA and has been fixed. Please have a look at JIRA issue for resolution.
https://jira.springsource.org/browse/DATAJPA-335

Starting asynchronous task via Spring TaskScheduler

I need to execute a task at 7.05am but I am getting an error.
This is the Controller I created.
#Service("myCtr")
public class MyController {
#Autowired
private TaskScheduler scheduler;
#Async
public void executeTaskT() {
scheduler.schedule(new MyWorker(),
new CronTrigger("5 7 * * *"));
}
}
MyWorker is implementing Runnable simply this way:
[...]
#Override
public void run() {
doWork();
}
private void doWork() { [...]
My scheduler configuration file is imported by the web-application-config.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<bean id="TaskScheduler"
class="org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler">
<property name="waitForTasksToCompleteOnShutdown" value="true" />
<property name="poolSize" value="1000" />
</bean>
</beans>
The error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyCtr': Injection
of autowired dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not autowire field: private
org.springframework.scheduling.TaskScheduler [...].MyController.scheduler; nested
exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type
[org.springframework.scheduling.TaskScheduler] 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
org.springframework.scheduling.TaskScheduler [...].MyController.scheduler; nested
exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type
[org.springframework.scheduling.TaskScheduler] 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.NoSuchBeanDefinitionException: No matching bean of type
[org.springframework.scheduling.TaskScheduler] 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)}
It appears that Spring can't find your TaskScheduler bean.
With INFO logging, you should be able to find your bean definition in the log during initialization. If not, make sure your configuration file is effectively read by doing further tests.
For your precise need, you can also use the following:
#Service
public class MyService {
#Scheduled(cron = "0 5 7 * * *")
public void myMethod() { ... }
}
With this configuration:
<task:annotation-driven scheduler="myScheduler"/>
<task:scheduler id="myScheduler" pool-size="1000"/>
And assuming MyService is properly seen as a bean, using e.g. Component Scan.

Resources