1、构造方法
User.java
public class User {
private String name;
public User() {
System.out.println("User类的无参数构造方法执行。");
}
}
xml
<!--使用构造方法进行实例化-->
<bean id="user" class="com.ray.spring6.beans.User"></bean>
Test.java
@Test
public void testInstantiation1(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
User user = applicationContext.getBean("user", User.class);
System.out.println(user);
}
2、简单工厂模式
Weapon.java
public class Weapon {
public Weapon() {
System.out.println("简单工厂模式执行。");
}
}
WeaponFactory.java
public class WeaponFactory {
private static Weapon attack(){
return new Weapon();
}
}
xml
<!--简单工厂模式:需要在Spring配置文件中告诉Spring框架,调用哪个类的哪个方法获取Bean-->
<bean id="weapon" class="com.ray.spring6.beans.WeaponFactory" factory-method="attack"></bean>
Test.java
@Test
public void testInstantiation2(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
Weapon weapon = applicationContext.getBean("weapon", Weapon.class);
System.out.println(weapon);
}
3、 通过factory-bean实例化
Gun.java
public class Gun {
public Gun() {
System.out.println("通过factory-bean实例化执行。");
}
}
GunFactory.java
public class GunFactory {
// 工厂方法模式中的具体工厂角色中的方法是:实例方法。
public Gun get(){
// 实际上new这个对象还是我们自己new的。
return new Gun();
}
}
xml
<!--工厂方法模式:通过factory-bean属性+factory-method属性来共同完成-->
<!--告诉Spring框架,调用哪个对象的哪个方法来获取Bean-->
<bean id="gunFactory" class="com.ray.spring6.beans.GunFactory"></bean>
<!--以下的配置很关键,factory-bean属性告诉Spring调用哪个对象,factory-method告诉Spring调用该对象的哪个方法-->
<bean id="gun" factory-bean="gunFactory" factory-method="get"></bean>
Test.java
@Test
public void testInstantiation3(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
Gun gun = applicationContext.getBean("gun", Gun.class);
System.out.println(gun);
}
4、通过FactoryBean接口实例化
Person.java
public class Person {
public Person() {
System.out.println("通过FactoryBean接口实例化");
}
}
PersonFactoryBean.java
public class PersonFactoryBean implements FactoryBean<Person> {
@Override
public Person getObject() throws Exception {
return new Person();
}
@Override
public Class<?> getObjectType() {
return null;
}
@Override
public boolean isSingleton() {
return FactoryBean.super.isSingleton();
}
}
xml
<!--第四种:通过FactoryBean来实现。实际上是工厂模式方法的简化-->
<!--由于编写的类实现了FactoryBean接口,所以这个类是一个特殊的类,不需要再手动指定:factory-bean属性和factory-method属性-->
<bean id="person" class="com.ray.spring6.beans.PersonFactoryBean"></bean>
Test.java
@Test
public void testInstantiation4(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
Person person = applicationContext.getBean("person", Person.class);
System.out.println(person);
}
以上四个实现效果截图 :