java - 使用spring初始化java枚举中的字段

标签 java spring enums

我需要通过 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/

相关文章:

java - 从内部类对象中获取外部类对象

Spring 5 Web 响应式(Reactive)编程 - 从流数据的 Spring 响应式(Reactive) Controller 解码 JSON 时出现 WebClient ClassCastException

java - 如何将JAVA Spring Framework部署到Tomcat

Python多行人工枚举使用范围

java - ORM:在 Hibernate/JPA 中用 JSON 代替 LOB

java - 使用命名空间但没有前缀的 JAXB 解码

java - Google Maps Android api v2 折线长度

java - 将嵌套对象发送到 Spring POST

java - 在Java中使用枚举制作评分表,然后允许用户输入数字成绩以输出字母成绩

c++ - 为什么无作用域枚举的声明可以编译?