tural
tural

Reputation: 320

injecting enum(Spring)

I have an enum and I need to inject it with spring bean.

my enum is:

public enum Status {


IN_PROCESS(1,"In process"),
DONE(0,"Successful"), 
CANNOT_DONE(2,"Unsuccessful");

private final int code;
private final String description;

private Status(int code, String description){
    this.code = code;
    this.description = description;
}

public int getCode() {
    return code;
}


public String getDescription() {
    return description;
}

}

what my bean.xml should look like for this enum..

thanks.

Upvotes: 2

Views: 3672

Answers (3)

Alex
Alex

Reputation: 11579

Check <util:constant/> here:
http://static.springsource.org/spring/docs/3.0.x/reference/xsd-config.html

Upvotes: 0

Michail Nikolaev
Michail Nikolaev

Reputation: 3775

Technically you may try to register enum as a bean like this:

@Configuration
class EnumProducer {
   @Bean
   Status inProgress() {
        return Status.IN_PROGRESS;
   }
}

and then inject it like:

@Autowired("inProgress") Status status.

But there is no any sense for doing it.

Upvotes: 1

Ralph
Ralph

Reputation: 120831

You can not create an Enum via its constructor from outside of this Enum (not in java and not in Spring) because Enum values are constants!

An Enum constructor can only be invoked from the Enum declarion itselve.

Of course you can use an instance of this Enum, even in Spring, but you can not create it:

public Class Entity {    
    public Entity(Status status) {...}
}

<bean name="entity" class="package.Entity">
   <property name="status" value="IN_PROCESS" />
</bean>

Upvotes: 1

Related Questions