SoFunction
Updated on 2025-04-06

IOC injection of date attributes and date formats through Setters

This example also involves the use of multiple configuration files in Spring, and also involves the injection of date formats-------------------------------------------------------------------------------------------------------
Date attribute class:
Copy the codeThe code is as follows:

package ;
import ;
public class DatePropertyInjection {
private Date date;
public Date getDate() {
return date;
}
public void setDate(Date date) {
= date;
}
}

Property Editor Class:
Copy the codeThe code is as follows:

package ;
import ;
import ;
import ;
import ;
/**
* Custom attribute editor handles properties of types
* @author Administrator
*
*/
public class PropertyEditor extends PropertyEditorSupport {
String format = "yyyy-MM-dd";
public void setFormat(String format) {
= format;
}
@Override
public void setAsText(String arg0) throws IllegalArgumentException {
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
try {
Date date = (arg0);
(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
();
}
}
}


Copy the codeThe code is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
xmlns:xsi="http:///2001/XMLSchema-instance"
xmlns:aop="/schema/aop"
xmlns:tx="/schema/tx"
xsi:schemaLocation="/schema/beans /schema/beans/spring-beans-2.
/schema/aop /schema/aop/spring-aop-2.
/schema/tx /schema/tx/spring-tx-2.">
<bean class="">
<property name="date">
<value>2009-8-28</value>
</property>
</bean>
</beans>


Copy the codeThe code is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
xmlns:xsi="http:///2001/XMLSchema-instance"
xmlns:aop="/schema/aop"
xmlns:tx="/schema/tx"
xsi:schemaLocation="/schema/beans /schema/beans/spring-beans-2.
/schema/aop /schema/aop/spring-aop-2.
/schema/tx /schema/tx/spring-tx-2.">
<!--
<bean class="">
<property name="date">
<value>2009-8-28</value>
</property>
</bean>
-->
<bean class="">
<property name="customEditors">
<map>
<entry key="">
<bean class="">
<!—Injecting date format-->
<property name="format" value="yyyy-MM-dd"/>
</bean>
</entry>
</map>
</property>
</bean>
</beans>

Test unit:
Copy the codeThe code is as follows:

package ;
import ;
import ;
import ;
public class InjectionTest extends TestCase {
BeanFactory factory;
protected void setUp() throws Exception {
//Use wildcards to read all configuration files starting with applicationContext
factory = new ClassPathXmlApplicationContext("applicationContext*.xml");
}
public void testInjection(){
DatePropertyInjection dateProp = (DatePropertyInjection)("dateProperty");
("date=" + ());
}
}