您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關spring中怎么利用FactoryBean配置Bean,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
Car.java
package com.gong.spring.beans.factoryBean;public class Car { private String name; private double price; public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public Car(String name, double price) { super(); this.name = name; this.price = price; } @Override public String toString() { return "Car [name=" + name + ", price=" + price + "]"; }}
CarFactoryBean.java
package com.gong.spring.beans.factoryBean;import org.springframework.beans.factory.FactoryBean;public class CarFactoryBean implements FactoryBean<Car> { private String name; public void setName(String name) { this.name = name; } //返回Bean的對象 @Override public Car getObject() throws Exception { // TODO Auto-generated method stub return new Car(name,200000); } //返回bean的類型 @Override public Class<?> getObjectType() { // TODO Auto-generated method stub return Car.class; } //是否是單例 @Override public boolean isSingleton() { // TODO Auto-generated method stub return true; }}
beans-factoryBean.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"> <bean id="car" class="com.gong.spring.beans.factoryBean.CarFactoryBean"> <property name="name" value="baoma"></property> </bean></beans>
Main.java
package com.gong.spring.beans.factoryBean;import org.springframework.context.support.ClassPathXmlApplicationContext;public class Main { public static void main(String[] args) { //1.創建spring的IOC容器對象 ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans-factoryBean.xml"); //2.從容器中獲取Bean實例 Car car = (Car) ctx.getBean("car"); System.out.println(car.toString()); ctx.close(); }}
關于spring中怎么利用FactoryBean配置Bean就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。