基于上一篇的项目配置,请浏览上一篇的一些基础 的配置
https://blog.csdn.net/weixin_43319279/article/details/103086312
1:创建实体类
package com.staticFactory;
public class Person {
public void say() {
System.out.println("Person say");
}
}
2:创建静态工厂类
package com.staticFactory;
public class MyBeanFactory {
public static Person createBean() {
return new Person();
}
}
3:配置spring.xml
<bean id="person" class="com.staticFactory.MyBeanFactory" factory-method="createBean"/>
为什么这里要配置spring呢?
测试类通过ClassPath,实例化并装载ApplicationContext ,通过实例化ApplicationContext,实现了spring中的ioc(控制反转)Di(依赖注入)。
4:创建测试类
package com.staticFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Demo {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
Person person = (Person) applicationContext.getBean("person");
person.say();
}
}
5:结果为: