spring学习之 工厂类和配置文件
作者:互联网
bean.properties
userMapper=top.chenyp.mapper.impl.UserMapperImpl
userService=top.chenyp.service.impl.UserServiceImpl
mapper
public interface UserMapper {
void findById(String id);
}
public class UserMapperImpl implements UserMapper {
@Override
public void findById(String id) {
System.out.println("hello");
}
}
service
public interface UserService {
void findById(String id);
}
public class UserServiceImpl implements UserService {
private UserMapper mapper = (UserMapper) BeanFactory.getBean("userMapper");
@Override
public void findById(String id) {
mapper.findById(id);
}
}
工厂类
public class BeanFactory {
private static Properties props;
//定义一个map对象,存储容器
private static Map<String,Object> beans;
static {
System.out.println("哈哈哈");
try {
props=new Properties();
InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
props.load(in);
beans=new HashMap<>();
//取出配置文件中所有的key
Enumeration<Object> keys = props.keys();
while (keys.hasMoreElements()) {
//取出每个key
String key = keys.nextElement().toString();
//根据key获取value;
String beanPath = props.getProperty(key);
//反射创建对象
Object value = Class.forName(beanPath).newInstance();
beans.put(key,value);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static Object getBean(String beanName){
return beans.get(beanName);
}
}
调用
public static void main(String[] args) {
UserService userMapper = (UserService) BeanFactory.getBean("userService");
userMapper.findById("123456");
}
标签:findById,String,配置文件,spring,工厂,static,key,id,public 来源: https://blog.csdn.net/qq_42794826/article/details/114375300