使用注解方式实现静态工厂方法实例化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();
}
}
运行结果:
以上是一个简单的小栗子
希望对你有用!