Flask接口签名sign原理与实例代码浅析
338
2023-02-27
Spring的实例工厂方法和静态工厂方法实例代码
Spring的实例工厂方法和静态工厂方法都可以用来实例化bean,本文我们就来看看相关实例。
静态工厂方法:直接调用静态方法可以返回Bean的实例
package com.zhu.string.factory;
import java.util.HashMap;
import java.util.Map;
public class StaticCarFactory {
/**
* 静态工厂方法:直接调用静态方法可以返回Bean的实例
*
*/
private static Map
static{
cars.put("audi", new Car(3000, "aodi"));
cars.put("fodo", new Car(3000, "aodi"));
}
//静态工厂方法
public static Car getCar(String name){
return cars.get(name);
}
}
实例工厂方法。即调用工厂本身,再调用工厂的实例方法来返回bean实例
package com.zhu.string.factory;
import java.util.HashMap;
import java.util.Map;
public class InstanceCarFactory {
/**
* 实例工厂方法。即调用工厂本身,再调用工厂的实例方法来返回bean实例
*/
private Map
public InstanceCarFactory() {
// TODO Auto-generated constructor stub
cars=new HashMap
cars.put("audi", new Car(1000,"audi"));
cars.put("dffdas", new Car(2000,"audi"));
}
public Car getCar(String brand){
return cars.get(brand);
}
}
beans-factory.xml
xmlns:xsi="http://w3.org/2001/XMLSchema-instance" xmlns:p="http://springframework.org/schema/p" xsi:schemaLocation="http://springframework.org/schema/beans http://springframework.org/schema/beans/spring-beans.xsd"> http:// class="com.zhu.string.factory.StaticCarFactory">
xmlns:xsi="http://w3.org/2001/XMLSchema-instance"
xmlns:p="http://springframework.org/schema/p"
xsi:schemaLocation="http://springframework.org/schema/beans
http://springframework.org/schema/beans/spring-beans.xsd">
http://
class="com.zhu.string.factory.StaticCarFactory">
class="com.zhu.string.factory.StaticCarFactory">
Car.java实体类
package com.zhu.string.factory;
public class Car {
private double price;
private String brand;
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getBrand() {
return brand;
}
public void setBrand(String GdnLbbrand) {
this.brand = brand;
}
@Override
public String toString() {
return "Car [brand=" + brand + ", price=" + price + "]";
}
public Car(){
System.out.println("cars....constructor");
}
public Car(double price, String brand) {
super();
this.price = price;
this.brand = brand;
}
}
Main.java
package com.zhu.string.factory;
import org.sprGdnLbingframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext cx=new ClassPathXmlApplicationContext("beans-
factory.xml");
Car car1=(Car) cx.getBean("car1");
System.out.println(car1);
Car car2=(Car) cx.getBean("car2");
System.out.println(carGdnLb2);
}
}
运行结果:
Car [brand=aodi, price=3000.0]
Car [brand=audi, price=1000.0]
总结
以上就是本文关于Spring的实例工厂方法和静态工厂方法实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~