I have some doubt about what exactly do these 3 Spring SpEL example:
1) FIRST EXAMPLE:
<bean id="rewardsDb" class="com.acme.RewardsTestDatabase">
<property name="keyGenerator" value="#{strategyBean.databaseKeyGenerator}" />
</bean>
It seems to me that this code snippet injet an inner property named databaseKeyGenerator (that is inside the strategyBean bean). So in this case SpEL is used to access to a specific bean property in the classica OO logic. Is it true?
2) SECOND EXAMPLE:
<bean id="strategyBean" class="com.acme.DefaultStrategies">
<property name="databaseKeyGenerator" ref="myKeyGenerator"/>
</bean>
It seems to me that SpEL is not used, or am I missing something?
3) THIRD EXAMPLE:
<bean id="taxCalculator" class="com.acme.TaxCalculator">
<property name="defaultLocale" value="#{ systemProperties['user.region'] }"/>
</bean> Equivalent
It is used to inject a property value taken from a property file
Is it correct or I a missing something or am I misinterpreting the SpEL logic?
The first and second examples come together. The second actually uses no SpEL at all. Its sole purpose is to help understand the first one. So you are not missing something regarding the first two.
As for the third one, systemProperties is a predefined variable and you use it to access system properties. Except from the standard VM system properties you can also access those that you pass with -D when starting the application.
You can access a property file the same way, after creating a bean to reference them, by using the bean id instead of systemProperties. For example
<util:properties id="appProps" location="classpath:application.properties" />
and then
<property name="propOne" value="#{appProps['some.property'] }"/>
I am working on an application where I have two classes both implementing a common interface. So in time of bean declaration, I am going to mark one of them primary in my app-context.xml file. I can achieve this by simply declaring the primary bean like this:
<bean id="oracleImpl" class="com.me.dao.OracleImpl" primary="true">
</bean>
Now I don't want to hard code which of the beans is going to be the primary bean, rather want to read the true/false value from a properties file. So I went like this:
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="oracleImpl" class="com.me.dao.OracleImpl" primary="${oracle.primary}">
</bean>
<bean id="pgsqlImpl" class="com.me.dao.PgsqlImpl" primary="${pgsql.primary}">
</bean>
The values of oracle.primary and pgsql.primary are defined in the file jdbc.properties along with other jdbc (non-boolean) properties.
But it doesn't work and says, "'${oracle.primary}' is not a valid value for 'boolean'"
I have a feeling it is something to do with the xsd validators. Browsing through this site and google gave me this much idea, but got no real solution. Can any body help?
This will not work.
As of 3.2.5.RELEASE only the following bean definition elemets support property placeholder:
parent name
bean class name
factory bean name
factory method name
scope
property values
indexed constructor arguments
generic constructor arguments
See the BeanDefinitionVisitor's visitBeanDefinition method for the details. This method is used by the PlaceholderConfigurerSupport.
I would recommend you to create a feature request in the spring issue management system.
PS: if you create an issue please add a comment to the issues url.
I am trying to get all the beans of the same type from an FileSystemXmlApplicationContext.
I was using factory.getBeansOfType(SomeType.class) but I have noticed it only returns top-level beans, is there any other method I can use that would return all the beans of a given type, even nested beans?
Example usage:
<bean name="topLevelBean" class="SomeClass">
<property name="someProperty">
<bean bean="nestedBean" class="SomeClass">
</property>
</bean>
Calling factory.getBeansOfType(SomeClass.class) returns only topLevelBean but not nestedBean.
Documentation of getBeansOfType says it only returns top-level beans.
My question is: is there any method that returns all beans of the desired type.
I can get access to all the beans by implementing the BeanPostProcessor interface and adding it to the spring context file.
I'm not sure but possibly BeanFactoryUtils#beansOfTypeIncludingAncestors() might return those (doc doesn't say).
I am confused between ref and depends-on attribute in Spring.I read the spring doc but I am still confused.I wish to know the exact difference between the two and in which case which one shall be used.
From the official documentation: http://docs.spring.io/spring/docs/3.2.x/javadoc-api/org/springframework/context/annotation/DependsOn.html
Beans on which the current bean depends. Any beans specified are guaranteed to be created by the container before this bean. Used infrequently in cases where a bean does not explicitly depend on another through properties or constructor arguments, but rather depends on the side effects of another bean's initialisation.
Perhaps an example of a situation where depends-on is needed would help. I use Spring to load and wire my beans. Here is an example bean definition:
<bean id="myBean" class="my.package.Class">
<property name="destination" value="bean:otherBeanId?method=doSomething"/>
</bean>
<bean id="otherBeanId" class="my.package.OtherClass"/>
Notice that the property value is a string, which references otherBeanId. Because of the way this variable is resolved, Spring doesn't learn of the dependency, so it may destroy otherBeanId then myBean. This may leave myBean in a broken state for a little while.
I can use depends on to fix this problem as follows:
<bean id="myBean" class="my.package.Class" depends-on="otherBeanId">
<property name="destination" value="bean:otherBeanId?method=doSomething"/>
</bean>
There might be a situation where a bean might be a property in another bean i.e; the property bean is directly involved in the bean definition as a property in such case we refer the beans with ref attribute.
There might be a situation where in a bean instantiation is required for the other bean to be successfully created, the other bean is not a property of the bean under definition, in such case we make use of the depends-on attribute.
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;
}
}