Bean
db.properties
StudentServiceImpl=com.ycz.service.impl.StudentServiceImpl
StudentServiceImpl2=com.ycz.service.impl.StudentServiceImpl2
StudentService
package com.ycz.service;/*
@author ycz
@date 2021-10-14-15:17
*/
public interface StudentService {
void add();
void update();
}
StudentServiceImpl
package com.ycz.service.impl;/*
@author ycz
@date 2021-10-14-15:17
*/
import com.ycz.service.StudentService;
public class StudentServiceImpl2 implements StudentService {
@Override
public void add() {
System.out.println("add222的方法");
}
@Override
public void update() {
System.out.println("更新2222的方法");
}
}
编写Factory
package com.ycz.factory;/*
@author ycz
@date 2021-10-14-15:19
*/
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class SpringBeanFactory {
private static Properties pp;
static {
try {
pp=new Properties();
pp.load(ClassLoader.getSystemResourceAsStream("db.properties"));
// String studentServiceImpl = pp.getProperty("StudentServiceImpl");
// System.out.println(studentServiceImpl);
} catch (IOException e) {
e.printStackTrace();
}
}
public static Object getBean(String BeanName) throws Exception {
String bean = pp.getProperty(BeanName);
Class<?> aClass = Class.forName(bean);
Object obj = aClass.getDeclaredConstructor().newInstance();
return obj;
}
}
测试:
@Test
public void t3() throws Exception {
StudentService studentServiceImpl =
(StudentService) SpringBeanFactory.getBean("StudentServiceImpl2");
studentServiceImpl.add();
}
结果:
add222的方法
\