我是Spring的新手,但经过一个多小时的搜索,我没有找到答案。我正在制作一个简单的卡片组,但无法使用两个枚举作为构造函数中的参数实例化Card对象。 Spring可以枚举吗?我可以不硬连接config类吗?这是我的代码:
@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: {}
由于您注释了@Component
类的Card
,因此Spring试图在应用程序上下文中创建bean,并且由于您声明了参数构造函数,因此将没有默认的构造函数可用
public Card(EnumValue v, EnumSuit s) {
value = v;
suit = s;
}
因此从@Component
类中删除Card
,并且对于Enum
类EnumValue
也存在相同的错误,您可以添加默认构造函数或删除@Component
EnumValue(){
}