我是 Spring 新手,但在搜索了一个多小时后我还没有找到答案。我正在制作一副简单的纸牌,但我无法让我的 Card 对象在构造函数中使用两个枚举作为参数进行实例化。Spring可以使用枚举吗?我不能在配置类中硬连线吗?这是我的代码:
@Component
public class Card {
EnumValue value;
EnumSuit suit;
public Card(EnumValue v, EnumSuit s) {
value = v;
suit = s;
}
public EnumValue getValue() {
return value;
}
public void setValue(EnumValue value) {
this.value = value;
}
public EnumSuit getSuit() {
return suit;
}
public void setSuit(EnumSuit suit) {
this.suit = suit;
}
@Override
public String toString() {
return String.format("[%s][%s]", value.getShortName(), suit.getShortName());
}
}
@Component
public enum EnumValue {
ACE("A",1), TWO("2", 2), THREE("3", 3), FOUR("4", 4), FIVE("5", 5), SIX("6", 6), SEVEN("7", 7),
EIGHT("8", 8), NINE("9", 9), TEN("T", 10), JACK("J", 10), QUEEN("Q", 10), KING("K", 10);
private String shortName;
private int points;
EnumValue(String name, int score){
shortName = name;
points = score;
}
public String getShortName() {
return shortName;
}
public void setShortName(String shortName) {
this.shortName = shortName;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
}
@Component
public enum EnumSuit {
CLUBS, DIAMONDS, HEARTS, SPADES;
public String getShortName() {
return this.toString().substring(0,1);
}
}
@Configuration
@ComponentScan(basePackages = "com.betterstuff.learnspring")
public class AppConfig {
@Bean
public Card getSampleCard() {
return new Card(EnumValue.ACE, EnumSuit.CLUBS);
}
}
public class App {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
Card obj = (Card) context.getBean(Card.class);
System.out.println("My Card is: " + obj.toString());
}
}
我收到错误消息:
WARNING: Exception encountered during context initialization - cancelling refresh attempt: UnsatisfiedDependencyException: Error creating bean with name 'card' defined in file [...\Card.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is NoSuchBeanDefinitionException: No qualifying bean of type 'com...EnumValue' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Exception in thread "main" UnsatisfiedDependencyException: Error creating bean with name 'card' defined in file [...\Card.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is NoSuchBeanDefinitionException: No qualifying bean of type 'com...EnumValue' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}