在Spring Boot Scheduler App

时间:2017-10-19 13:05:04

标签: spring spring-boot maven-plugin spring-scheduled

我正在开发一个spring boot scheduler应用程序。调度工作正常,但我无法从另一个模块自动装配业务逻辑bean。我收到错误“无法自动装配MyService”

这是一个多模块弹簧启动项目。

MyService是另一个模块中的服务实现

Application.java

@SpringBootApplication
public class Application  {

public static void main(String[] args) {


    ApplicationContext ctx = new AnnotationConfigApplicationContext(AppScheduler.class);
}
  }

AppScheduler.java

@EnableScheduling
public class AppScheduler{

@Autowired
MyService serv;

private static final SimpleDateFormat dateFormat = new SimpleDateFormat(
        "MM/dd/yyyy HH:mm:ss");

@Scheduled(cron = "*/5 * * * * *")
public void performTaskUsingCron() throws Exception {

    serv.test();
}
}

的pom.xml

<parent>
    <artifactId>test</artifactId>
    <groupId>my.service</groupId>  
 <version>1.0.0-SNAPSHOT</version>      
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>test_BATCH</artifactId>

<dependencies>
    <dependency>
        <groupId>my.service</groupId>
        <artifactId>test_SERVICE</artifactId>
        <version>${project.version}</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

3 个答案:

答案 0 :(得分:0)

你在MyService中使用@Service吗?

@Service
public class MyService {
...
}

答案 1 :(得分:0)

我不确定错误是什么,但我猜您必须扫描其他模块中的组件。

@SpringBootApplication
@ComponentScan("co.uk.module.*")
public class Application  {

public static void main(String[] args) {
    ApplicationContext ctx = new AnnotationConfigApplicationContext(AppScheduler.class);
  }
}

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/ComponentScan.html

请注意,bean MyService必须具有@Service(或@Component)注释。

答案 2 :(得分:0)

我在你的课程中添加了一些东西,在这里工作得很好:

Application.class:

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

AppScheduler.class:

@Component
@EnableScheduling
public class AppScheduler {

    @Autowired
    private MyService serv;

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat(
            "MM/dd/yyyy HH:mm:ss");

    @Scheduled(cron = "*/5 * * * * *")
    public void performTaskUsingCron() throws Exception {

        serv.test();
    }
}

MyService.class:

@Service
public class MyService {
    public void test() {
        System.out.println("This is a test");
    }
}