Spring中使用FactoryBean配置注入Bean

发布于:2024-07-08 ⋅ 阅读:(45) ⋅ 点赞:(0)

spring通过FactoryBean配置可以将第三方框架整合到Spring中来,FactoryBean配置如下:
 

  1. 写一个用于注于的实体类,如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;
    	}
    
    }

  2. 在Spring配置文件中配置|
    <bean id="zs" class="test.spring.model.UserFactoryBean">
    		<constructor-arg value="zs"></constructor-arg>
    	</bean>
  3. 测试结果
    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);
    	}
    
    }


网站公告

今日签到

点亮在社区的每一天
去签到