我需要通过 spring 初始化 java 枚举中的“flag”字段:
public enum EntitySequenceType {
TypeOne(-1),
TypeTwo(-1000);
private boolean flag;
EntitySequenceType(long firstId){
System.out.println("enum's constructor: "+this.name()+" firstId="+firstId);
}
public void setFlag(boolean val) {
this.flag = val;
}
public boolean getFlag() {
return this.flag;
}
}
Spring 配置是:
<bean id="myEnum" class="com.maven.start.maven_spring.EntitySequenceType"
factory-method="valueOf">
<property name="flag" value="true"/>
<constructor-arg>
<value>TypeOne</value>
</constructor-arg>
</bean>
但是我遇到了一些问题,所以我有以下问题:
1.<constructor-arg>
中好像只能写一个值配置xml中的标签,我不明白为什么会这样。
2.我在调试代码的时候,发现spring在初始化bean的时候,虽然我只写了一个constructor-arg
config xml 中的值,构造函数被调用两次。怎么会发生这种情况?
3.在EntitySequenceType的构造函数中,我发现“flag”的值为null,为什么?如果enum实现了InitializingBean的话可以调用“afterPropertiesSet()”,但是不是每次构造enum类型时都会调用,那么有没有方法在spring设置完字段后调用,但是每次都会调用枚举类型被称为?
感谢您的回答!
最佳答案
It seems that I can only write a single value in the tag in the config xml, I can't figure out why it is like this.
与工厂方法
一起使用时,constructor-arg
值引用该工厂方法
的参数列表。 EntitySequenceType.valueOf(String)
仅采用一个参数,即 String
。
When I debugging the code, I found that when spring is initializing the bean, although I only write one constructor-arg value in the config xml, the constructor is called twice.How could this happen?
与任何其他类型一样,枚举类型在代码中首次引用时会加载并初始化其 .class
文件。 枚举
常量
TypeOne(-1),
TypeTwo(-1000);
实际上是编译字节码中的静态
字段。因此,它们在类初始化时也被初始化。这是两个构造函数调用,这就是您所看到的。
constructor-arg
值与这些构造函数无关,它与您的工厂方法
有关。
In the constructor of EntitySequenceType, I found that the "flag"'s value is null, why? There is "afterPropertiesSet()" can be called if the enum implements InitializingBean, but it is not called every time a enum type is constructed, so is there any method to be called after the field is set by spring, but is called every time a enum type is called?
它不能是null
,它是一个原始类型。您的属性将在调用并执行工厂方法
后设置。无需实现 InitializingBean
。
不要为此使用枚举
。枚举应该是常量。
关于java - 使用spring初始化java枚举中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21352756/