Spring_注解方式实现静态工厂方法实例化Bean_注解方式实例化工厂Bean

本文介绍了一种完全使用注解的方式,通过静态工厂方法实例化Spring框架中的Bean。具体步骤包括:创建学生类,定义学生工厂类并在其静态方法上添加@Bean注解,创建配置类并使用@Import导入静态工厂方法类。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用注解方式实现静态工厂方法实例化Bean

完全使用注解的方式实现静态工厂方法实例化Bean的例子:
1、创建一个学生类

package com.exec.Ioc.T3;

public class Student {
	private String name;
	private String sex;
	private String email;
	
	public Student(String name) {
		this.name=name;
	}
	public void getMessage() {
		System.out.println("姓名:"+this.name);
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}
}

2、创建一个学生工厂类,在静态方法上添加@Bean注解

package com.exec.Ioc.T3;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

public class StudentFactory {
	@Bean
	public static Student getStudent(@Value("测试用例")String name) {
		return new Student(name);
	}
}

3、创建一个配置类,使用@Import注解导入静态工厂方法类

package com.exec.Ioc.T3;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import(StudentFactory.class)
public class Bean_Config {

}

在配置类中不需要实例化学生类的@Bean注解,我们使用静态工厂的方法实例化学生类Bean,因此此处不需要再写代码,只要导入静态方法实例化的类和表示这是个注解类@Configuration即可
4、测试结果

package com.exec.Ioc.T3;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
//测试类
public class Test_Main {
	public static void main(String[] args) {
		ApplicationContext apc=new AnnotationConfigApplicationContext(Bean_Config.class);
		Student st=apc.getBean("getStudent",Student.class);
		st.getMessage();
	}
}

运行结果:
运行结果
以上是一个简单的小栗子希望对你有用!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值