spring通过FactoryBean配置可以将第三方框架整合到Spring中来,FactoryBean配置如下:
- 写一个用于注于的实体类,如User,并对这个类写一个实现FactoryBean的中间类(UserFactoryBean)
User类/** *Description: *author: ljd *@date 2024年7月2日 *@version 1.0 */ package test.spring.model; 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 + "]"; } public User() { super(); } }
UserFactoryBean类
/** *Description: *author: ljd *@date 2024年7月3日 *@version 1.0 */ package test.spring.model; import org.springframework.beans.factory.FactoryBean; public class UserFactoryBean implements FactoryBean<User> { private String type; public UserFactoryBean(String type) { super(); this.type = type; } //返回Bean对象 @Override public User getObject() throws Exception { return new User(1,type); } //返回Bean类型 @Override public Class<?> getObjectType() { // TODO Auto-generated method stub return User.class; } }
- 在Spring配置文件中配置|
<bean id="zs" class="test.spring.model.UserFactoryBean"> <constructor-arg value="zs"></constructor-arg> </bean>
- 测试结果
package testSpring; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import test.spring.model.User; public class TestSpring { @Test public void testUser() { ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml"); User user=(User) ac.getBean("zs"); System.out.println(user); } }