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?
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.
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.)
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.
@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 .
You can use Spring Expression Language:
<constructor-arg value = "#{elvis.age}" />
or without elvis
bean:
<constructor-arg value = "#{T(com.xyz.Elvis).INSTANCE.age}" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With