inject java.sql.Time object into a bean - spring xml dependency injection - java

I need to inject a java.sql.Time object into a Subject bean using xml based dependency injection.
This is my Subject class definition.
public class Subject{
private java.sql.Time startedTime;
}
In Java code this will be the way to do it.
Subject subject = new Subject();
Time startedTime = Time.valueOf("HH:MM:SS");
subject.setStartedTime(startedTime);
But now I need to do the same injecting that Time object in the Subject bean via xml
<bean id="startedTime" class="mx.com.project.Subject">
<property name="startedTime">
<!-- java.sql.Time injection-->
</property>
</bean>
I've been looking for a while on the internet but have not found any example on this. Just one to inject a Date property into a Customer object by converting a formatted string "yyyy-MM-dd" to a Date object using SimpleDateFormat.parse("yyyy-MM-dd")
It makes me think there should be a similar way to convert a String to Time object. This is the example I found.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="dateFormat" class="java.text.SimpleDateFormat">
<constructor-arg value="yyyy-MM-dd" />
</bean>
<bean id="customer" class="com.mkyong.common.Customer">
<property name="date">
<bean factory-bean="dateFormat" factory-method="parse">
<constructor-arg value="2010-01-31" />
</bean>
</property>
</bean>
</beans>
By the way, the link to the above example

Perform the conversion from String to Time in your object.
public class Subject
{
private java.sql.Time startedTime;
// blah. your stuff.
public void setStartedTimeValue(final String startedTimeValue)
{
startedTime = Time.valueof(startedTimeValue);
}
}
<bean id="startedTime" class="mx.com.project.Subject">
<property name="startedTimeValue" value="20:14:37"/>
</bean>

The first right answer to this question.
<property name="startedTime">
<bean factory-method="valueOf" class="java.sql.Time">
<constructor-arg value="16:00:00" />
</bean>
</property>

Related

Spring date datatype [duplicate]

Consider this simple example -
public class Person
{
private String name;
private Date dateOfBirth;
// getters and setters here...
}
In order to initialize Person as a Spring bean, I can write the following.
<bean id = "Michael" class = "com.sampleDomainName.Person">
<property name = "name" value = "Michael" />
</bean>
But in the above bean definition, how can I set the dateOfBirth?
For eg. I want to set the dateOfBirth as
1998-05-07
Treat it like any other POJO (which is is)
<property name="dateOfBirth">
<bean class="java.util.Date" />
</property>
If you need to use an explicit value (such as 1975-04-10), then simply call one of the other constructors (although those which take year-month-day are deprecated). You could also use an explicit java.beans.PropertyEditor which Spring rolls with already (see section 6.4.2; note that you can write your own editors and register them for your own types). You need to register the CustomEditorConfigurer in your config:
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.util.Date"
value="org.springframework.beans.propertyeditors.CustomDateEditor"/>
</map>
</property>
</bean>
Then your data looks like:
<property name="dateOfBirth" value="1975-04-10" />
I might add that Date is not an appropriate data type to store a date-of-birth because Date is really an instant-in-time. You might like to look at Joda and use the LocalDate class.
One of the answers mentioned here is useful, but it needs additional information. The constructor arguments for the CustomDateEditor need to be supplied.
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.util.Date"> <ref local = "customDateEditor" />
</entry>
</map>
</property>
</bean>
<bean id = "customDateEditor" class="org.springframework.beans.propertyeditors.CustomDateEditor">
<constructor-arg>
<bean class="java.text.SimpleDateFormat">
<constructor-arg value="yyyy-MM-dd" />
</bean>
</constructor-arg>
<constructor-arg value="true" />
</bean>
Now we can do
<property name="dateOfBirth" value="1998-05-07" />
Spring inject Date into bean property – CustomDateEditor
This paper give two suggestions:
Factory bean
CustomDateEditor
I suggest the "Factory Bean" because the CustomDateEditor is not supported in Spring 4.0+ and the Factory Bean is easy enough to use.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="dateFormat" class="java.text.SimpleDateFormat">
<constructor-arg value="yyyy-MM-dd" />
</bean>
<bean id="customer" class="com.mkyong.common.Customer">
<property name="date">
<bean factory-bean="dateFormat" factory-method="parse">
<constructor-arg value="2010-01-31" />
</bean>
</property>
</bean>
</beans>
Use a CustomDateEditor. It's been in Spring since the early days.

Java Spring IOC bean creation value

I need a bean like this
<bean id="studentWithSchool" class="com.model.Student" scope="prototype">
<property name="school">
<bean class="com.model.School" scope="prototype"/>
</property>
</bean>
This is OK.
My problem is I have the student returning from a method from a different bean.
I usually load the bean like this when is a property.
<property name='beanProperty' value='#{anotherBean.getBeanProperty()}'/>
But in this case I need the new bean itself being set from the other bean method (School object is returned from another bean method).
This is what I try, and of course this is wrong:
<bean id="studentWithSchool" class="com.model.Student" scope="prototype" value='#{anotherBean.getBeanProperty()}'>
<property name="school">
<bean class="com.model.School" scope="prototype"/>
</property>
</bean>
Is there any workaround?
If I understand you correctly, the studentWithSchool is created and returned by a method in anotherBean. If that's the case, you can use a factory-method:
<bean id="studentWithSchool" factory-bean="anotherBean" factory-method="getBeanProperty" scope="prototype" />
I believe you are trying to use factory patter with Spring . For that you can use factory bean from spring.
<bean id="studentWithSchool" factory-bean="anotherBeanStaticFactory" factory- method="createBeanProperty" scope="prototype"
<property name="school">
<bean class="com.model.School" scope="prototype"/>
</property>
For more detail you can use below link :-
http://docs.spring.io/spring-framework/docs/2.5.6/api/org/springframework/beans/factory/BeanFactory.html

How to define a List bean in Spring?

I'm using Spring to define stages in my application. It's configured that the necessary class (here called Configurator) is injected with the stages.
Now I need the List of Stages in another class, named LoginBean. The Configurator doesn't offer access to his List of Stages.
I cannot change the class Configurator.
My Idea:
Define a new bean called Stages and inject it to Configurator and LoginBean.
My problem with this idea is that I don't know how to transform this property:
<property ...>
<list>
<bean ... >...</bean>
<bean ... >...</bean>
<bean ... >...</bean>
</list>
</property>
into a bean.
Something like this does not work:
<bean id="stages" class="java.util.ArrayList">
Can anybody help me with this?
Import the spring util namespace. Then you can define a list bean as follows:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-2.5.xsd">
<util:list id="myList" value-type="java.lang.String">
<value>foo</value>
<value>bar</value>
</util:list>
The value-type is the generics type to be used, and is optional. You can also specify the list implementation class using the attribute list-class.
Here is one method:
<bean id="stage1" class="Stageclass"/>
<bean id="stage2" class="Stageclass"/>
<bean id="stages" class="java.util.ArrayList">
<constructor-arg>
<list>
<ref bean="stage1" />
<ref bean="stage2" />
</list>
</constructor-arg>
</bean>
<bean id="someBean"
class="com.somePackage.SomeClass">
<property name="myList">
<list value-type="com.somePackage.TypeForList">
<ref bean="someBeanInTheList"/>
<ref bean="someOtherBeanInTheList"/>
<ref bean="someThirdBeanInTheList"/>
</list>
</property>
</bean>
And in SomeClass:
class SomeClass {
List<TypeForList> myList;
#Required
public void setMyList(List<TypeForList> myList) {
this.myList = myList;
}
}
Another option is to use JavaConfig. Assuming that all stages are already registered as spring beans you just have to:
#Autowired
private List<Stage> stages;
and spring will automatically inject them into this list. If you need to preserve order (upper solution doesn't do that) you can do it in that way:
#Configuration
public class MyConfiguration {
#Autowired
private Stage1 stage1;
#Autowired
private Stage2 stage2;
#Bean
public List<Stage> stages() {
return Lists.newArrayList(stage1, stage2);
}
}
The other solution to preserve order is use a #Order annotation on beans. Then list will contain beans ordered by ascending annotation value.
#Bean
#Order(1)
public Stage stage1() {
return new Stage1();
}
#Bean
#Order(2)
public Stage stage2() {
return new Stage2();
}
Stacker posed a great answer, I would go one step farther to make it more dynamic and use Spring 3 EL Expression.
<bean id="listBean" class="java.util.ArrayList">
<constructor-arg>
<value>#{springDAOBean.getGenericListFoo()}</value>
</constructor-arg>
</bean>
I was trying to figure out how I could do this with the util:list but couldn't get it work due to conversion errors.
I think you may be looking for org.springframework.beans.factory.config.ListFactoryBean.
You declare a ListFactoryBean instance, providing the list to be instantiated as a property withe a <list> element as its value, and give the bean an id attribute. Then, each time you use the declared id as a ref or similar in some other bean declaration, a new copy of the list is instantiated. You can also specify the List class to be used.
<bean id="student1" class="com.spring.assin2.Student">
<property name="name" value="ram"></property>
<property name="id" value="1"></property>
<property name="listTest">
<list value-type="java.util.List">
<ref bean="test1"/>
<ref bean="test2"/>
</list>
</property>
</bean>
define those beans(test1,test2) afterwards :)
Inject list of strings.
Suppose you have Countries model class that take list of strings like below.
public class Countries {
private List<String> countries;
public List<String> getCountries() {
return countries;
}
public void setCountries(List<String> countries) {
this.countries = countries;
}
}
Following xml definition define a bean and inject list of countries.
<bean id="demoCountryCapitals" name="demoCountryCapitals" class="com.sample.pojo.Countries">
<property name="countries">
<list>
<value>Iceland</value>
<value>India</value>
<value>Sri Lanka</value>
<value>Russia</value>
</list>
</property>
</bean>
Reference link
Inject list of Pojos
Suppose if you have model class like below.
public class Country {
private String name;
private String capital;
.....
.....
}
public class Countries {
private List<Country> favoriteCountries;
public List<Country> getFavoriteCountries() {
return favoriteCountries;
}
public void setFavoriteCountries(List<Country> favoriteCountries) {
this.favoriteCountries = favoriteCountries;
}
}
Bean Definitions.
<bean id="india" class="com.sample.pojo.Country">
<property name="name" value="India" />
<property name="capital" value="New Delhi" />
</bean>
<bean id="russia" class="com.sample.pojo.Country">
<property name="name" value="Russia" />
<property name="capital" value="Moscow" />
</bean>
<bean id="demoCountryCapitals" name="demoCountryCapitals" class="com.sample.pojo.Countries">
<property name="favoriteCountries">
<list>
<ref bean="india" />
<ref bean="russia" />
</list>
</property>
</bean>
Reference Link.
Use the util namespace, you will be able to register the list as a bean in your application context. You can then reuse the list to inject it in other bean definitions.
As an addition to Jakub's answer, if you plan to use JavaConfig, you can also autowire that way:
import com.google.common.collect.Lists;
import java.util.List;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;
<...>
#Configuration
public class MyConfiguration {
#Bean
public List<Stage> stages(final Stage1 stage1, final Stage2 stage2) {
return Lists.newArrayList(stage1, stage2);
}
}
You just remove id out of beans inside <list> tag. Like this:
<property name="listStaff">
<list>
<bean class="com.test.entity.Staff">
<constructor-arg name="name" value = "Jonh"/>
<constructor-arg name="age" value = "30"/>
</bean>
<bean class="com.test.entity.Staff">
<constructor-arg name="name" value = "Jam"/>
<constructor-arg name="age" value = "21"/>
</bean>
</list>
</property>
Use list-class attribute in util:list to make a standalone list of any particular type. for example if you want to make list of type ArrayList:
<util:list id="namesList" list-class="java.util.ArrayList" value-type="java.lang.String">
<value>Abhay</value>
<value>ankit</value>
<value>Akshansh</value>
<value>Db</value>
</util:list>
or if you want to make a list of type LinkedList then :
<util:list id="namesList" list-class="java.util.LinkedList" value-type="java.lang.String">
<value>Abhay</value>
<value>ankit</value>
<value>Akshansh</value>
<value>Db</value>
</util:list>
And this is how to inject set in some property in Spring:
<bean id="process"
class="biz.bsoft.processing">
<property name="stages">
<set value-type="biz.bsoft.AbstractStage">
<ref bean="stageReady"/>
<ref bean="stageSteady"/>
<ref bean="stageGo"/>
</set>
</property>
</bean>

Spring: Getting FactoryBean object instead of FactoryBean.getObject()

Short question: If I have class that impelemnts FactoryBean interface, how can I get from FactoryBean object itself instead of FactoryBean.getObject()?
Long question: I have to use 3-rd party Spring based library which is hardly use FactoryBean interface. Right now I always must configure 2 beans:
<!-- Case 1-->
<bean id="XYZ" class="FactoryBean1" scope="prototype">
<property name="steps">
<bean class="FactoryBean2">
<property name="itemReader" ref="aName"/>
</bean>
</property>
</bean>
<bean id="aName" class="com.package.ClassName1" scope="prototype">
<property name="objectContext">
<bean class="com.package.ABC"/>
</property>
</bean>
<!-- Case 2-->
<bean id="XYZ2" class="FactoryBean1" scope="prototype">
<property name="steps">
<bean class="FactoryBean2">
<property name="itemReader" ref="aName2"/>
</bean>
</property>
</bean>
<bean id="aName2" class="com.package.ClassName1" scope="prototype">
<property name="objectContext">
<bean class="com.package.QWE"/>
</property>
</bean>
Actyually defintion of a bean with name "XYZ" (compare with "XYZ2") never will be changed, but because of factory nature I must copy the code for each configuration.
Definition of a bean with name "aName" always will be new (i.e. each configuration will have own objectContext value).
I would like to simplify the configuration have a single factory bean (remove "XYZ2" and rid of link to "aName"):
<bean id="XYZ" class="FactoryBean1" scope="prototype">
<property name="steps">
<bean class="FactoryBean2"/>
</property>
</bean>
<bean id="aName" class="com.package.ClassName1" scope="prototype">
<property name="objectContext">
<bean class="com.package.ABC"/>
</property>
</bean>
<bean id="aName2" class="com.package.ClassName1" scope="prototype">
<property name="objectContext">
<bean class="com.package.QWE"/>
</property>
</bean>
Unfortunately, it's not as simple as I expect. I suppose to glue factory (i.e. XYZ bean from the example) with necessary objects (i.e. "aName", "aName2") at runtime.
The approach doesn't work because when I ask Spring for FactoryBean object it returns to me FactoryBean.getObject() which impossible to instanciate at that time because of missing itemReader value.
I hope that SpringSource foresee my case I can somehome "hook" FactoryBean.getObject() call to provide all necessary properties at runtime.
Another complexity that disturb me a bit it's chains of Factories (Factory1 get an object from Factory2 that I have to "hook" at runtime).
Any ideas will be appreciated.
It's the & (ampersand), not the At-symbol, see Spring Framework documentation: Customizing instantiation logic using FactoryBeans
<property name="factoryBean" ref="&theFactoryBean" />
You can get the factory bean itself using the & syntax in the spring config:
<property name="factoryBean" ref="&theFactoryBean" />
as opposed to:
<property name="createdBean" ref="theFactoryBean" />

spring: set property of one bean by reading the property of another bean?

Is it possible to set the property of one bean by reading the property of another bean? For instance, suppose I had:
class A {
void setList(List list);
}
class B {
List getList();
}
I would like Spring to instantiate both classes, and call A's setList method, passing in the result of calling B's getList method. The Spring configuration might look something like:
<bean id="b" class="B"/>
<bean id"a" class="A">
<property name="list" ref="b" ref-property="list"/>
</bean>
Alas, this made-up XML does not work.
Why not just inject B into A? Because I do not want to introduce the extra dependency. A is only dependent List, not on B.
in addition to #Kevin's answer if you are using spring 3.0 it is possible to do this with the new spring expression language
<bean id="a" class="A">
<property name="list"
value="#{b.list}"/>
</bean>
spring 3.0 documentation
There are a couple of ways. Here is one:
<bean id="b" class="B"/>
<bean id="a" class="A">
<property name="list">
<bean class="org.springframework.beans.factory.config.PropertyPathFactoryBean">
<property name="targetObject" ref="b"/>
<property name="propertyPath" value="list"/>
</bean>
</property>
</bean>
Also see the <util:property-path/> element
If you are trying to do the same for a constructor then do this.
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg type="javax.sql.DataSource" value="#{jdbc.dataSource}">
</constructor-arg>
</bean>
Here "jdbc" is as mentioned below that has property "dataSource" with getter and setter and initilized as:
<bean id="jdbc" class="com.la.activator.DataSourceProvider">
<property name="myDataSourcePool" ref="dsPoolService"/>
</bean>

Categories