Getting started with spring -- three ways to create bean s

[*] static engineering method to create bean s [*] instan...
Static engineering method creation bean
Static engineering method creation bean
spring's FactoryBean creation bean

[*] static engineering method to create bean s

[*] instance engineering method creation bean

[*] spring's FactoryBean creation bean

Static engineering method creation bean

You can return the bean instance directly by using the static method of the class

public class StaticCarFactory { private static Map<String, Car> cars = new HashMap<String, Car>(); static { cars.put("audi", new Car("audi", 20000)); cars.put("ford", new Car("ford", 40000)); } public static Car getCar(String name) { return cars.get(name); } }
<! -- configure bean s through static engineering methods Note: instead of configuring static engineering method instances, configure bean instances Class attribute: refers to the static engineering method full class name Factory method: point to static engineering method Constructor Arg: if the static engineering method needs to pass in parameters, use constructor Arg: to configure parameters --> <bean id="car1" factory-method="getCar"> <constructor-arg name="name" value="audi"/> </bean>

Static engineering method creation bean

First create the project itself, and call the instance method of the project

public class InstanceCarFactory { private static Map<String, Car> cars; public InstanceCarFactory() { cars = new HashMap<String, Car>(); cars.put("audi", new Car("audi", 20000)); cars.put("ford", new Car("ford", 40000)); } public Car getCar(String name) { return cars.get(name); } }
<!--Create by engineering method of instance bean--> <!--Configuration engineering example--> <bean id="carFactory"/> <bean id="car2" factory-bean="carFactory" factory-method="getCar"> <constructor-arg name="name" value="ford"/> </bean>

spring's FactoryBean creation bean

Implement FactoryBean interface

public class CarFactoryBean implements FactoryBean<Car> { private String brand; public void setBrand(String brand) { this.brand = brand; } /** * @return bean object * @throws Exception abnormal */ @Override public Car getObject() throws Exception { return new Car(brand, 40000); } /** * @return bean Type of */ @Override public Class<?> getObjectType() { return Car.class; } /** * @return Single case or not */ @Override public boolean isSingleton() { return true; } }
<bean id="car3"> <property name="brand" value="CarFactoryBean"/> </bean>

4 May 2020, 15:26 | Views: 6131

Add new comment

For adding a comment, please log in
or create account

0 comments