通过FactoryBean来配置Bean
关键代码:
实现FactoryBean<T>接口
详细:
User.java:
package com.shuoeasy.test; public class User { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public User(int id, String name) { super(); this.id = id; this.name = name; } @Override public String toString() { return "User [id=" + id + ", name=" + name + "]"; } }
UserFactoryBean.java:
package com.shuoeasy.test; import org.springframework.beans.factory.FactoryBean; public class UserFactoryBean implements FactoryBean<User>{ private int id; public void setId(int id) { this.id = id; } /** * 返回bean对象 */ public User getObject() throws Exception { return new User(this.id,"张三"); } /** * 返回bean的类型 */ public Class<?> getObjectType() { return User.class; } /** * 是否单实例 */ public boolean isSingleton() { return true; } }
bean.xml:
<?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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 通过FactoryBean来配置Bean的实例, 虽然配置的是FactoryBean,但实际上返回User类型。 --> <bean id="user1" class="com.shuoeasy.test.UserFactoryBean"> <property name="id" value="1001"></property> </bean> </beans>
输出:
user1->User [id=1001, name=张三]