Spring中的工厂bean
【摘要】
1.普通bean与工厂bean
Spring 有两种类型 bean,一种普通 bean,另外一种工厂 bean(FactoryBean)
普通 bean:在配置文件中定义 bean 类型就是返回类型工...
1.普通bean与工厂bean
Spring 有两种类型 bean,一种普通 bean,另外一种工厂 bean(FactoryBean)
- 普通 bean:在配置文件中定义 bean 类型就是返回类型
- 工厂 bean:在配置文件定义 bean 类型可以和返回类型不一样
2.工厂bean的步骤
- 创建类,让这个类作为工厂 bean,实现接口 FactoryBean
public class MyFactoryBean implements FactoryBean<Student> {
//定义返回 bean
@Override
public Student getObject() throws Exception {
Student student = new Student();
student.setName("工厂bean");
return student;
}
@Override
public Class<?> getObjectType() {
return null;
}
@Override
public boolean isSingleton() {
return false;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 实现接口里面的方法,在实现的方法中定义返回的 bean 类型
//定义返回 bean
@Override
public Student getObject() throws Exception {
Student student = new Student();
student.setName("工厂bean");
return student;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
代码示例:
Student类:
public class Student {
private String name;
private int age;
private String gender;
public Student() {
}
public Student(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
'}';
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
xml文件:
<?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="myFactoryBean" class="iocbean.byxml.factorybean.MyFactoryBean">
</bean>
</beans>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
测试类:
public class TestDemo {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("iocbean/byxml/factorybean/bean.xml");
Student bean = context.getBean("myFactoryBean", Student.class);
System.out.println(bean);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
输出结果:
Student{name='工厂bean', age=0, gender='null'}
Process finished with exit code 0
- 1
- 2
- 3
- 4
文章来源: blog.csdn.net,作者:Mr.Yushiwen,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/MrYushiwen/article/details/110818537
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)