Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring syntax for setting a Class object?

Tags:

java

spring

Is there a way to set a property in spring to, not an instance of a class, but the class object itself? i.e.

Rather than

<bean>    <property name="prototype" class="a.b.c.Foo">... 

giving you an instance of "Foo", something like:

<bean>   <property name="prototype" class="java.lang.Class" value="a.b.c.Foo.class"... 

edit: best (working) solution so far - use the normal instantiation and derive the class in the setter. In terms of solutions I think this we'd describe this as "cheating":

<bean class="Bar">    <property name="prototype" class="a.b.c.Foo">...   public class Bar{         public void setPrototype(Object o){                 this.prototypeClass=o.getClass(); 

edit: dtsazza's method works as well.

edit: pedromarce's method works as well.

like image 351
Steve B. Avatar asked Oct 21 '09 14:10

Steve B.


People also ask

What is the use of @bean in Spring boot?

One of the most important annotations in spring is the @Bean annotation which is applied on a method to specify that it returns a bean to be managed by Spring context. Spring Bean annotation is usually declared in Configuration classes methods. This annotation is also a part of the spring core framework.

Does @configuration create a bean?

Yes. @Configuration annotated class will register as a spring bean.


2 Answers

<bean>    <property name="x">       <value type="java.lang.Class">a.b.c.Foo</value>    </property>  </bean> 

That should work.

like image 129
pedromarce Avatar answered Oct 14 '22 09:10

pedromarce


You could certainly use the static factory method Class.forName(), if there's no more elegant syntax (and I don't believe there is):

<property name="x">    <bean class="java.lang.Class" factory-method="forName">       <constructor-arg value="a.b.c.Foo"/>    </bean> </property> 
like image 31
Andrzej Doyle Avatar answered Oct 14 '22 09:10

Andrzej Doyle