尽管适当导入,为什么注释无法解决?

时间:2018-04-17 09:43:50

标签: java spring eclipse maven

我已经成功添加了spring依赖的maven项目。使用时会解析组件注释,但Autowired注释会生成错误,尽管它出现在构建路径中。我该如何解决这个问题?

enter image description here

第一个组件类

import org.springframework.stereotype.Component;

@Component
public class Comp1 {
}

第二个组件类

import org.springframework.stereotype.Component;
//error: The import org.springframework.beans.factory.annotation.Autowired cannot be resolved
import org.springframework.beans.factory.annotation.Autowired;

@Component
public class Comp2 {
    @Autowired // error: Autowired cannot be resolved to a type
    private Comp1 comp1;

    public Comp1 getComp1() {
        return comp1;
    }
}

的pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>Spr</groupId>
  <artifactId>Spr</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.0.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>5.0.5.RELEASE</version>
    </dependency>
  </dependencies>

</project>

3 个答案:

答案 0 :(得分:0)

添加Spring bean依赖项,因为Autowire注释是spring-bean依赖项的一部分:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>your-version</version>
</dependency>

答案 1 :(得分:0)

添加这些依赖项

</dependencies>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>5.0.5.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.0.5.RELEASE</version>
</dependency>

答案 2 :(得分:0)

删除本地maven存储库文件夹(.m2)并重新加载它,解决了问题。