Spring syntax for setting a Class object? - java

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.

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

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>

No. With a bean tag you instruct Spring on how to instantiate a class.

Would <property name="x" class="a.b.c.Foo.class"> work? That should be an instance of a Class object...

Related

How to create java.util.Optional<T> object from Spring bean?

Java
public class MyObject{}
public class MyFactory{
private Optional<MyObject> myproperty;
public Optional<MyObject> getMyproperty{...}
public void setMyproperty{...}
}
Spring config xml (doesn't work)
<bean id="myproperty" class="java.util.Optional">
<constructor-arg>
<value>com.MyObject</value>
</constructor-arg>
</bean>
<bean id="myfactory" class="com.Myfactory">
<property name="myproperty" ref="myproperty" />
</bean>
Does spring support generics beans?
The reason for using Optional is it provide some useful features such as checking value if null. You can complete checking and further action in one line of code.
getMyproperty().ifPresent(id -> call.setId(id));
Seems the problem have nothing to do with generics.
You simply need to properly tell Spring to create the bean using a factory method, as Optional can only be created though factory methods. Something like:
<bean id="myproperty" class="java.util.Optional" factory-method="of">
<constructor-arg type="java.lang.Object" value="com.MyObject" />
</bean>
for which it is supposed to mean creating the myproperty bean by Optional.of(com.MyObject.class) (Change the factory-method to ofNullable if that's the one you want to use)
Another option is to use SpEL (Spring Expression Language):
<bean id="mybean" ...>
<property name="optProp" value="#{ T(java.util.Optional).of( #wrapme) }"/>
</bean>
Where "wrapme" is the name of a bean defined elsewhere that you want to wrap in java.util.Optional.

How to create a Path bean

I need my Spring application context to include a bean that is a (Java 7) Path object, with a fixed (known) path-name. What XML bean definition should I use?
This kind of bean has some complications:
Path is an interface, and Path objects should be created using the Paths.get(String...) static factory method.
The static factory method also has an overloaded variant, Paths.get(URI).
As the object is-a Path, the class of the bean should be Path:
<bean name="myPath" class="java.nio.file.Path"/>
I need to indicate the static factory method to use, which would seem to require a factory-method attribute. But the factory method belongs to the java.nio.file.Paths class rather than the java.nio.file.Path class, so I assume the following would not work:
<bean name="myPath" class="java.nio.file.Path"
factory-method="java.nio.file.Paths.get"/>
Lastly, I need to give the arguments for the factory method. How do I do that? Using nested constructor-arg (sic) elements? So, something like this?
<bean name="myPath" class="java.nio.file.Path"
factory-method="java.nio.file.Paths.get">
<constructor-arg value="/my/path/name"/>
</bean>
But that does not work: Springs throws a BeanCreationException, complaining of "No matching factory method found: factory method 'java.nio.file.Paths.get()'."
After some experimenting with pingw33n's answer, I found this worked:
<bean id="myPath" class="java.nio.file.Paths" factory-method="get">
<constructor-arg value="/my/path" />
<constructor-arg><array /></constructor-arg>
</bean>
Note:
Give the name of the factory class, rather than the object class, as the value of the class attribute.
Give an extra empty array constructor argument, to force selection of the correct overload of the factory method. This avoids having to go the round-about route of instead constructing a file URI.
Well , i had the same problem as you , and my solution was ...
<bean id="ThreadRunnerConfigFile" class="java.nio.file.Paths" factory-method="get" c:_0="ThreadRunnerConfigFileStr" />
Dont forget to include the c namespace on your .xml configuration file
Something like below should help.
<bean id="myPath" class="java.nio.file.Paths" factory-method="get">
<constructor-arg type="java.lang.String" value="/my/path/name" />
</bean>
Try this:
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="staticMethod"><value>java.nio.file.Paths.get</value></property>
<property name="arguments">
<array>
<value>/my/path/name</value>
<array/>
</array>
</property>
</bean>

Determine for which aggregation a bean is created

I have the following definition:
<bean id="logger" factory-method="createLog" scope="prototype" class="com.test.beans.LogBean" ></bean>
<bean id="aone" class="com.test.beans.AggregationOne">
<property name="log" ref="logger"></property>
</bean>
<bean id="atwo" class="com.test.beans.AggregationTwo">
<property name="log" ref="logger"></property>
</bean>
Is it possible to recognize for which object (aone or atwo) bean 'logger' is being created?
Why I'm asking: in a legacy application I have one log instance for all classes. I want to change level for some packages, but can't do that (except using filters, what I don't want). For that purpose I want to utilize some spring magic, if it exists for that case )
I don't think it can be done this way. What you could try is a BeanPostProcessor implementation which detects common logger object in beans and replaces it with a specific one.

How to #Autowire a bean which is hidden behind ProxyFactoryBean?

Let's say we have two beans, defined in Spring
<bean class="foo.A"/>
<bean class="foo.B"/>
public class A {
#Autowired
private B b;
}
public class B {
public void foo() {
...
}
}
What I want to achieve is the interception of all calls to B.foo(). Looking at documentation, I wrote interceptor C and changed the definition of bean B as follows:
public class C implements org.springframework.aop.MethodBeforeAdvice {
public void before(final Method method, final Object[] args, final Object target) {
// interception logic goes here
}
}
<bean class="foo.C"/>
<bean class="org.springframework.aop.framework.ProxyFactoryBean" scope="prototype">
<property name="proxyTargetClass" value="true"/>
<property name="singleton" value="false"/>
<property name="target">
<bean class="foo.B" scope="prototype"/>
</property>
<property name="interceptorNames">
<list>
<value>foo.C</value>
</list>
</property>
</bean>
Problem: when starting up, Spring container complains: No matching bean of type [foo.B] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. In other words, it can't inject B into A because B is hidden behind org.springframework.aop.framework.ProxyFactoryBean and no longer "automagically" recognized. If I replace the definition into a simple class=foo.B, container starts fine. What's the best way to solve this?
Bonus question: is it possible to implement interception of B.foo() without involvement of ProxyFactoryBean and only using annotations (preferably without involvement of <aop:...)?
Define an interface for foo.B (e.g. foo.BInterface) and use foo.BInterface in the class A.
Also pay attention that Autowired injections are done only once. So if foo.A is singleton, it will receive only the first created instance of foo.B, while you want it to be a prototype.
Answer to bonus: Yes, but it may be more complicated. As a possible solution you can implement BeanPostProcessor. In the implementation you can replace the foo.B with dynamic proxy. So basically you do the same, but instead of using <aop: you do it yourself using basic Spring functionality. And again: you don't solve the "prototype is not autowired" problem and you still need an interface.
Perhaps you want to have the Bean 'foo.B' defined outside of the ProxyFactoryBean, and refer to it from the target property.
<bean class="foo.C"/>
<bean id="fooB" class="foo.B" scope="prototype"/>
<bean class="org.springframework.aop.framework.ProxyFactoryBean" scope="prototype">
<property name="proxyTargetClass" value="true"/>
<property name="singleton" value="false"/>
<property name="target" ref="fooB"/>
<property name="interceptorNames">
<list>
<value>foo.C</value>
</list>
</property>
</bean>
Tarlog's answer is correct, but to make it more clear:
you should wire objects by their interface, not by their class:
public class A {
#Autowired
private C b;
}
public class B implements C{
public void foo() {
...
}
}

spring - constructor injection and overriding parent definition of nested bean

I've read the Spring 3 reference on inheriting bean definitions, but I'm confused about what is possible and not possible.
For example, a bean that takes a collaborator bean, configured with the value 12
<bean name="beanService12" class="SomeSevice">
<constructor-arg index="0" ref="serviceCollaborator1"/>
</bean>
<bean name="serviceCollaborator1" class="SomeCollaborator">
<constructor-arg index="0" value="12"/>
<!-- more cargs, more beans, more flavor -->
</bean>
I'd then like to be able to create similar beans, with slightly different configured collaborators. Can I do something like
<bean name="beanService13" parent="beanService12">
<constructor-arg index="0">
<bean>
<constructor-arg index="0" value="13"/>
</bean>
</constructor>
</bean>
I'm not sure this is possible and, if it were, it feels a bit clunky. Is there a nicer way to override small parts of a large nested bean definition? It seems the child bean has to know quite a lot about the parent, e.g. constructor index.
This is a toy example - in practice the service is a large bean definition relying on many other collaborator beans, which have also other bean dependencies. For example, a chain of handlers were created with each bean referencing the next in the chain, which references the next. I want to create an almost identical chain with some small changes to handlers in the middle, how do I it?
I'd prefer not to change the structure - the service beans use collaborators to perform their function, but I can add properties and use property injection if that helps.
This is a repeated pattern, would creating a custom schema help?
Thanks for any advice!
EDIT: The nub of my question is, if I have a really large bean definition, with a complex hiearchy of beans being created (bean having properites that are bean etc.), and I want to create a bean that is almost the same with a few changes, how to I do it? Please mention if your solution has to use properites, or if constructor injection can be used.
Nested vs. top-level beans are not the issue (in fact, I think all the beans are top level in practice.)
EDIT2: Thank you for your answers so far. A FactoryBean might be the answer, since that will reduce the complexity of the spring context, and allow me to specify just the differences as parameters to the factory. But, pushing a chunk of context back into code doesn't feel right. I've heard that spring can be used with scripts, e.g. groovy - does that provide an alternative? Could the factory be created in groovy?
I'm not entirely sure what you are trying to achieve. I don't think you can achieve exactly what you want without creating your own custom schema (which is non-trivial for nested structures), but the following example is probably pretty close without doing that.
First, define an abstract bean to use as a template for your outer bean (my example uses a Car as the outer bean and an Engine as the inner bean), giving it default values that all other beans can inherit:
<bean id="defaultCar" class="Car" abstract="true">
<property name="make" value="Honda"/>
<property name="model" value="Civic"/>
<property name="color" value="Green"/>
<property name="numberOfWheels" value="4"/>
<property name="engine" ref="defaultEngine"/>
</bean>
Since all Honda Civics have the same engine (in my world, where I know nothing about cars), I give it a default nested engine bean. Unfortunately, a bean cannot reference an abstract bean, so the default engine cannot be abstract. I've defined a concrete bean for the engine, but mark it as lazy-init so it will not actually be instantiated unless another bean uses it:
<bean id="defaultEngine" class="Engine" lazy-init="true">
<property name="numberOfCylinders" value="4"/>
<property name="volume" value="400"/>
<property name="weight" value="475"/>
</bean>
Now I can define my specific car, taking all the default values by referencing the bean where they are defined via parent:
<bean id="myCar" parent="defaultCar"/>
My wife has a car just like mine, except its a different model (again, I know nothing about cars - let's assume the engines are the same even though in real life they probably are not). Instead of redefining a bunch of beans/properties, I just extend the default car definition again, but override one of its properties:
<bean id="myWifesCar" parent="defaultCar">
<property name="model" value="Odyssey"/>
</bean>
My sister has the same car as my wife (really), but it has a different color. I can extend a concrete bean and override one or more properties on it:
<bean id="mySistersCar" parent="myWifesCar">
<property name="color" value="Silver"/>
</bean>
If I liked racing minivans, I might consider getting one with a bigger engine. Here I extend a minivan bean, overriding its default engine with a new engine. This new engine extends the default engine, overriding a few properties:
<bean id="supedUpMiniVan" parent="myWifesCar">
<property name="engine">
<bean parent="defaultEngine">
<property name="volume" value="600"/>
<property name="weight" value="750"/>
</bean>
</property>
</bean>
You can also do this more concisely by using nested properties:
<bean id="supedUpMiniVan" parent="myWifesCar">
<property name="engine.volume" value="600"/>
<property name="engine.weight" value="750"/>
</bean>
This will use the "defaultEngine". However, if you were to create two cars this way, each with different property values, the behavior will not be correct. This is because the two cars would be sharing the same engine instance, with the second car overriding the property settings set on the first car. This can be remedied by marking the defaultEngine as a "prototype", which instantiates a new one each time it is referenced:
<bean id="defaultEngine" class="Engine" scope="prototype">
<property name="numberOfCylinders" value="4"/>
<property name="volume" value="400"/>
<property name="weight" value="475"/>
</bean>
I think this example gives the basic idea. If your data structure is complex, you might define multiple abstract beans, or create several different abstract hierarchies - especially if your bean hierarchy is deeper than two beans.
Side note: my example uses properties, which I believe are much clearer to understand, both in Spring xml and in Java code. However, the exact same technique works for constructors, factory methods, etc.
Your example will not work as specified, because the nested bean definition has no class or parent specified. You'd need to add more information, like this:
<bean name="beanService13" parent="beanService12">
<constructor-arg index="0">
<bean parent="beanBaseNested">
<constructor-arg index="0" value="13"/>
</bean>
</constructor>
Although I'm not sure if it's valid to refer to nested beans by name like that.
Nested bean definitions should be treated with caution; they can quickly escalate into unreadability. Consider defining the inner beans as top-level beans instead, which would make the outer bean definitions easier to read.
As for the child beans needing to know the constructor index of the parent bean, that's a more basic problem with Java constructor injection, in that Java constructor arguments cannot be referred to by name, only index. Setter injection is almost always more readable, at the cost of losing the finality of constructor injection.
A custom schema is always an option, as you mentioned, although it's a bit of a pain to set up. If you find yourself using this pattern a lot, it might be worth the effort.
Have you thought of using a factory instead?
You can config beans to have a factory and you could encode the varying parameters in the factory creation...
To expand on the factory pattern from Patrick: you can use a prototype bean to get pre-wired dependencies:
<bean id="protoBean" scope="prototype">
<property name="dependency1" ref="some bean" />
<property name="dependency2" ref="some other bean" />
...
</bean>
Now, this works best if you use setter injection (rather than constructor arguments), i'm not sure you can even do it you require constructor args.
public class PrototypeConsumingBean implements ApplicationContextAware {
public void dynmicallyCreateService(String serviceParam) {
// creates a new instance because scope="prototype"
MyService newServiceInstance = (MyService)springContext.getBean("protoBean");
newServiceInstance.setParam(serviceParam);
newServiceInstance.mySetup();
myServices.add(newServiceInstance);
}
public void setApplicationContext(ApplicationContext ctx) {
m_springContext = ctx;
}
}

Categories