为什么Gradle编译在此示例中失败?

时间:2015-02-01 17:27:23

标签: java spring compilation gradle annotations

我正在读一本书Introducing Spring Framework,我被困在第一个例子上。我之前从未使用过Gradle。不知何故,编译器并不理解我的代码中使用的注释。即使我在gradle.build文件中使用了spring依赖项。

为了完整起见,我将发布此示例中的所有4个文件。

的build.gradle:

apply plugin: 'java'
apply plugin: 'application'

mainClassName = System.getProperty("mainClass")

repositories {
    mavenCentral()
}

dependencies {
    compile 'org.springframework:spring-context:4.0.5.RELEASE'
}

MessageService.java:

package com.apress.isf.spring;

public interface MessageService {

 public String getMessage();

}

HelloWorldMessage.java:

package com.apress.isf.spring;



public class HelloWorldMessage implements MessageService {

 public String getMessage(){

 return "Hello World";

 }

}

Application.java:

package com.apress.isf.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

@Configuration
@ComponentScan
public class Application {

 @Bean
 MessageService helloWorldMessageService() {

    return new HelloWorldMessage();

 }

 public static void main(String[] args) {

    ApplicationContext context = new AnnotationConfigApplicationContext(Application.class);
    MessageService service =  context.getBean(MessageService.class);

    System.out.println(service.getMessage());

    }

}

我用以下代码运行示例:

gradle run -DmainClass=com.apress.isf.spring.Application

使用Ubuntu。

结果是:

~/src/main/java/com/apress/isf/spring/Application.java:7: error: cannot find symbol
@Configuration
 ^
  symbol: class Configuration
~/src/main/java/com/apress/isf/spring/Application.java:8: error: cannot find symbol
@ComponentScan
 ^
  symbol: class ComponentScan
2 errors
:compileJava FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':compileJava'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 5.025 secs

任何人都可以帮我运行这个例子吗?问候。

1 个答案:

答案 0 :(得分:8)

我认为您缺少Application类顶部的Configuration和ComponentScan的import语句:

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;