在此示例中,通过@Produce注释进行依赖注入

时间:2014-10-05 05:33:53

标签: java java-ee dependency-injection

这是一个简单的数字猜测示例,用于演示Java EE 7中的依赖注入。我不太了解的是Game.java中的两个注入字段," maxNumber"和" randomNumber"。我知道可以注入它们,因为Generator.java中有两个@produce方法,@ Produce int next()和@Produce int getMaxNumber()。

然而,方法名称" next()"不匹配" randumNumber"注入Game.java。这是如何工作的?

另外,我尝试更改" getMaxNumber()"其他东西" getMMMaxNumber()"在Generator.java中。该程序仍然正常。所以,我真的不明白这两个字段是如何从Generator.java注入Game.java的。

请帮助理解这一点。非常感谢提前。

Game.java

package org.jboss.as.quickstarts.numberguess;
@SuppressWarnings("serial")
@Named
@SessionScoped
public class Game implements Serializable {
/**
 * The number that the user needs to guess
 */
private int number;

/**
 * The users latest guess
 */
private int guess;

/**
 * The smallest number guessed so far (so we can track the valid guess range).
 */
private int smallest;

/**
 * The largest number guessed so far
 */
private int biggest;

/**
 * The number of guesses remaining
 */
private int remainingGuesses;

/**
 * The maximum number we should ask them to guess
 */
@Inject
@MaxNumber
private int maxNumber;

/**
 * The random number to guess
 */
@Inject
@Random
Instance<Integer> randomNumber;

public Game() {
}

public int getNumber() {
    return number;
}

public int getGuess() {
    return guess;
}

public void setGuess(int guess) {
    this.guess = guess;
}

public int getSmallest() {
    return smallest;
}

public int getBiggest() {
    return biggest;
}

public int getRemainingGuesses() {
    return remainingGuesses;
}


@PostConstruct
public void reset() {
    this.smallest = 0;
    this.guess = 0;
    this.remainingGuesses = 10;
    this.biggest = maxNumber;
    this.number = randomNumber.get();
}
}

Generator.java

@SuppressWarnings("serial")
@ApplicationScoped
public class Generator implements Serializable {

private java.util.Random random = new java.util.Random(System.currentTimeMillis());

private int maxNumber = 100;

java.util.Random getRandom() {
    return random;
}

@Produces
@Random
int next() {
    // a number between 1 and 100
    return getRandom().nextInt(maxNumber - 1) + 1;
}

@Produces
@MaxNumber
int getMaxNumber() {
    return maxNumber;
}
}

MaxNumber.java

@Target({ TYPE, METHOD, PARAMETER, FIELD })
@Retention(RUNTIME)
@Documented
@Qualifier
public @interface MaxNumber {

}

Random.java

@Target({ TYPE, METHOD, PARAMETER, FIELD })
@Retention(RUNTIME)
@Documented
@Qualifier
public @interface Random {

}

1 个答案:

答案 0 :(得分:0)

注入不是通过方法名称完成的,而是通过限定符 @Random@MaxNumber来区分这两个值。 @Produce - 注释方法的相应方法名称不相关,只需返回匹配类型。