Establish Student.java
package com.lql.srping04; /** * @author: lql * @date: 2019.10.28 * Description: */ public class Student { private String name; private Integer age; @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } public Student() { } public Student(String name, Integer age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
Establish StudentFactoryBean.java
package com.lql.srping04; import org.springframework.beans.factory.FactoryBean; /** * @author: lql * @date: 2019.10.28 * Description: * Created with IntelliJ IDEA */ public class StudentFactoryBean implements FactoryBean<Student> { /** * * @return 返回bean的对象 * @throws Exception */ @Override public Student getObject() throws Exception { return new Student("张无忌",17); } / ** * * @return return bean type * / @Override public Class <?> GetObjectType () { return Student. Class ; } / ** * * @return whether singleton * / @Override public Boolean isSingleton () { return to true ; } }
Configuration:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="student" class="com.lql.srping04.StudentFactoryBean"></bean> </beans>
test:
package com.lql.srping04; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @author: lql * @date: 2019.10.28 * Description: */ public class StudetnTest { public static void main(String[] args) { ApplicationContext app = new ClassPathXmlApplicationContext("spring04.xml"); // Student student = app.getBean("studentfactory", Student.class); Student student = app.getBean("student", Student.class); System.out.println(student); } }
result:
Information: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@37bba400: startup date [Mon Oct 28 15:03:41 GMT + 08: 00 2019]; root of context hierarchy
October 28, 2019 3:03:41 pm org .springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
information: Loading the XML from the bean class path Resource Definitions [spring04.xml] Student {name = 'zhangwuji', age = 17}
Note that: custom FactoryBean need to achieve "FactoryBean" interface. Examples are returned getObject () Returns an instance of