首页 > 代码库 > Spring初学之FactoryBean配置Bean
Spring初学之FactoryBean配置Bean
实体bean:
Car.java:
package spring.beans.factorybean; public class Car { private String name; private int price; public Car(String name, int price) { super(); this.name = name; this.price = price; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } @Override public String toString() { return "Car [name=" + name + ", price=" + price + "]"; } }
CarFactoryBean.java:
package spring.beans.factorybean; import org.springframework.beans.factory.FactoryBean; /** * 通过factoryBean来创建实例 * @author Administrator * */ public class CarFactoryBean implements FactoryBean<Car> { private String name; private int price; public void setName(String name) { this.name = name; } public void setPrice(int price) { this.price = price; } /** * 返回一个bean实例 */ @Override public Car getObject() throws Exception { return new Car(name, price); } /** * 返回bean的类型 */ @Override public Class<?> getObjectType() { // TODO Auto-generated method stub return Car.class; } /** * 是否是单实例 */ @Override public boolean isSingleton() { // TODO Auto-generated method stub return true; } }
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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 通过factorybean来创建实例 我们设置的是CarFactoryBean的属性, 返回的是Car的实例 --> <bean id="car" class="spring.beans.factorybean.CarFactoryBean"> <property name="name" value="奥迪"></property> <property name="price" value="300000"></property> </bean> </beans>
Spring初学之FactoryBean配置Bean
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。