java - 为什么在这个例子中 Gradle 编译失败?

标签 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'
}

消息服务.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";

 }

}

应用程序.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

谁能帮我运行这个例子?问候。

最佳答案

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

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

关于java - 为什么在这个例子中 Gradle 编译失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28265558/

相关文章:

java - 使用 JDBC JobStore 的 Quartz 调度器

java - 从java运行linux命令

Spring @MVC和@RequestParam验证

java - com.mysql.jdbc.exceptions.jdbc4.CommunicationsException : Communications link failure AND BeanEntityManager error

具有特殊字符的 JAVA 模式类

java - 如何扩展 ArrayAdapter 以打印已解析的 JSON?

java - 带有静态访问修饰符的最终变量

java - ResolverStyle.STRICT 在 `@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)` 中不起作用

groovy - 使用javac进行编译时发生编译错误| Groovy

ios-charts:无法将库导入新项目