2014-10-05 250 views
0

這是一個簡單的數字猜測的例子來演示Java EE 7中的依賴注入。我不太明白的是Game.java中的兩個注入字段,「maxNumber」和「randomNumber」。我知道它們可以被注入,因爲在Generator.java中有兩個@produce方法,@Produce int next()和@Produce int getMaxNumber()。在這個例子中通過@Produce註釋的依賴注入

但是,方法名稱「next()」與Game.java中注入的「randumNumber」不匹配。這是如何工作的?

此外,我試着在Generator.java中將「getMaxNumber()」更改爲其他「getMMMaxNumber()」。該程序仍然正常工作。所以,我真的不明白這兩個字段是如何從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 { 

} 

回答

0

注射不是通過方法名稱完成的,而是兩個值的區別在於它們的限定符@Random@MaxNumber。 -annotated方法的相應方法名稱不相關,它們只需要返回一個匹配類型。