在XML文件中配置
测试代码
/**
* 不同类型的继承
*/
ApplicationContext context=new
ClassPathXmlApplicationContext("applicationContext.xml"); Talk
topic=context.getBean("talk",Talk.class);
System.out.println(topic.getNames());
System.out.println(topic.getTitle());
运行结果:
talk被创建
reply被创建
[123, 245]
xxxx
工厂TopicFactory.java
package factory; import org.springframework.beans.factory.FactoryBean; import auto.Topic; public class TopicFactory implements FactoryBean{ private Topic topic; //返回对象 @Override public Topic getObject() throws Exception { //单例模式 if(topic==null){ topic=new Topic(); } return topic; } //返回对象类型 @Override public Class getObjectType() { return Topic.class; } //判断对象是否是单例 @Override public boolean isSingleton() { return true; } }
bean.xml
// 工厂
ApplicationContext context = new ClassPathXmlApplicationContext(
"bean.xml"); Topic topic = context.getBean("topic", Topic.class);
topic.setId("110"); System.out.println(topic.getId()); Topic topic1 =
context.getBean("topic", Topic.class);
System.out.println(topic1.getId());
运行结果:
110
110