3

我正在创建一个示例项目,如MKyong 的教程中所述。我正在使用日食。当我创建项目时,我找不到任何方法来编写@Value注释。

我知道这看起来很愚蠢,但我根本无法解决这个问题。你能帮忙吗?

...
import org.springframework.beans.factory.annotation.*;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

@Component ("newSession")
public class Session implements DisposableBean, InitializingBean {

    @Value ("3232")
    private int id;
...

pom.xml:

...
<properties>
    <spring.version>3.0.5.RELEASE</spring.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring</artifactId>
        <version>2.5.6</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>
    <!-- Spring 3 dependencies -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
</dependencies>
....

为糟糕的缩进(大量复制粘贴)和愚蠢的问题道歉。

4

2 回答 2

4

原答案:

@org.springframework.beans.factory.annotation.Value注释可以在 spring-beans jar 中找到。将以下依赖项添加到您的 pom 应该可以解决问题:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>${spring.version}</version>
</dependency>

更新:

我相信这个问题只是一个类路径问题。依赖org.springframework:spring:2.5.6,也有包org.springframework.beans.factory.annotation,但是没有Value注解类。我的假设是 Eclipse 类路径被搞砸了。如果您更新类路径(即 mvn eclipse:eclipse),您的问题应该得到解决。

你还需要旧的 Spring 依赖项吗?如果没有,那么最好将其删除。

顺便说一句,@BalajiV 是绝对正确的,您不需要显式依赖,spring-beans因为它将通过spring-context依赖暂时引入。必须承认,如果我个人对来自特定 jar 的类(在本例中为Value类)有编译时依赖项,那么我总是在我的 pom 中明确定义对该 jar 的依赖项,而不是依赖另一个 3rd 方依赖项来提供它为了我。我知道这不太可能发生,但如果在未来的版本中spring-context他们删除了对的依赖,spring-beans那么当我升级到较新版本时,我的模块将不再工作。

于 2013-06-06T07:18:22.440 回答
0

如果我们在pom.xml中提到了spring-context,则没有必要在 pom.xml 中将spring-beans作为单独的依赖项提及。这将负责下载许多与 spring 相关的 jar,其中之一是spring-beans,这是我们需要使用@Value注释的。

关于您的问题,是 @Value 行上的编译错误还是没有将值注入到您的变量中?我问你这个问题是因为你的代码片段在我在 Eclipse 中的示例 maven 项目上运行良好,并且与你在这里给出的 pom.xml 相同。

于 2013-06-06T07:39:48.900 回答