在用spring管理我们的类的时候有时候希望有些属性值是来源于一些配置文件,系统属性,或者一些方法调用的结果,对于前两种使用方式可以使用spring的PropertyPlaceholderConfigurer类来注入,这些内容已经在前面的文章中说过,这里就不在重复了。这里就针对第三种情况做一些说明,其实在spring中是提供了对这种需求的解决方案的,那就是使用org.springframework.beans.factory.config.MethodInvokingFactoryBean类来生成需要注入的bean的属性,下面是一个例子
MyBean.java一个普通的POJO类
- importorg.apache.commons.lang.builder.ToStringBuilder;
- publicclassMyBean{
- privateStringname;
- privateStringjavaVersion;
- publicStringgetName(){
- returnname;
- }
- publicvoidsetName(Stringname){
- this.name=name;
- }
- publicStringgetJavaVersion(){
- returnjavaVersion;
- }
- publicvoidsetJavaVersion(StringjavaVersion){
- this.javaVersion=javaVersion;
- }
- @Override
- publicStringtoString(){
- returnToStringBuilder.reflectionToString(this);
- }
- }
MyBeanNameProvider.java提供一个静态方法用来生成MyBean类的name属性,同理非静态方法也是可以的,参考本例子中javaVersion属性定义
- publicclassMyBeanNameProvider{
- publicstaticStringgetName(){
- return""+System.currentTimeMillis();
- }
- }
spring.xml
- <?xmlversion="1.0"encoding="UTF-8"?>
- <beansxmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.0.xsd
- http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-2.0.xsd"
- default-lazy-init="true">
- <beanid="myBean"class="MyBean">
- <propertyname="name"><reflocal="myBeanName"/></property>
- <propertyname="javaVersion"><reflocal="javaVersion"/></property>
- </bean>
- <beanid="sysProps"class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
- <propertyname="targetClass">
- <value>java.lang.System</value>
- </property>
- <propertyname="targetMethod">
- <value>getProperties</value>
- </property>
- </bean>
- <beanid="javaVersion"class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
- <propertyname="targetObject">
- <reflocal="sysProps"/>
- </property>
- <propertyname="targetMethod">
- <value>getProperty</value>
- </property>
- <propertyname="arguments">
- <list>
- <value>java.version</value>
- </list>
- </property>
- </bean>
- <beanid="myBeanName"class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
- <propertyname="staticMethod"><value>MyBeanNameProvider.getName</value></property>
- </bean>
- </beans>
Test.java一个测试类
- importorg.springframework.context.ApplicationContext;
- importorg.springframework.context.support.ClassPathXmlApplicationContext;
- publicclassTest{
- publicstaticvoidmain(String[]args){
- ApplicationContextctx=newClassPathXmlApplicationContext("spring.xml");
- MyBeanmyBean=(MyBean)ctx.getBean("myBean");
- System.out.println(myBean);
- }
- }
运行Test类,就可以看到MyBean的两个属性都通过spring配置的方式注入到了类中