Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Spring enum bean and passing the value of a method call

Tags:

java

enums

spring

I have this Singleton:

   public enum Elvis {
       INSTANCE;
       private int age;

       public int getAge() {
           return age;
       }
   }

I know how to create the enum bean in spring:

   <bean id="elvis" class="com.xyz.Elvis" factory-method="valueOf">
           <constructor-arg>
               <value>INSTANCE</value>
           </constructor-arg>
   </bean> 

How do I pass the int returned by INSTANCE.getAge() into another beans constructor?

like image 218
DarVar Avatar asked May 22 '12 13:05

DarVar


People also ask

How do you inject the value of a bean property in Spring?

Most people know that you can use @Autowired to tell Spring to inject one object into another when it loads your application context. A lesser known nugget of information is that you can also use the @Value annotation to inject values from a property file into a bean's attributes.

Can an enum be a bean?

Enums are not beans because they have no default constructor (hence CDI does not know how to construct them,) and there is no standard way to resolve which enumerated value should be injected by default (Unless there is only one value, but this is still not supported due to the lack of default constructor.)

Can @bean method be private?

Any @Bean annotated method, which is not public (i.e. with protected, private and default visibility), will create a 'hidden' bean. In the example above, mainBean has been configured with both publicBean and hiddenBean.

What is @bean method?

@Bean is a method-level annotation and a direct analog of the XML <bean/> element. The annotation supports most of the attributes offered by <bean/> , such as: init-method , destroy-method , autowiring , lazy-init , dependency-check , depends-on and scope .


1 Answers

You can use Spring Expression Language:

<constructor-arg value = "#{elvis.age}" />

or without elvis bean:

<constructor-arg value = "#{T(com.xyz.Elvis).INSTANCE.age}" />
like image 151
axtavt Avatar answered Oct 11 '22 13:10

axtavt