spring bean工厂模式
作者:互联网
#1.==============配置文件
bean.properties
#先写dao,再写service
UserDao=com.ghy.dao.impl.UserDaoImpl
UserService=com.ghy.service.impl.UserServiceImpl
#2.==============配置文件
import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Properties;
import java.util.Set;
/**
* @author ghy
* @version 1.0
* @date 2021-09-13
* @userd 使得Properties有序
*/
public class OrderedProperties extends Properties {
private static final long serialVersionUID = 4710927773256743817L;
private final LinkedHashSet<Object> keys = new LinkedHashSet<Object>();
@Override
public Enumeration<Object> keys() {
return Collections.<Object> enumeration(keys);
}
@Override
public Object put(Object key, Object value) {
keys.add(key);
return super.put(key, value);
}
@Override
public Set<Object> keySet() {
return keys;
}
/**
* 返回按照properties文件存储顺序的名称集合
* @return
*/
@Override
public Set<String> stringPropertyNames() {
Set<String> set = new LinkedHashSet<String>();
for (Object key : this.keys) {
set.add((String) key);
}
return set;
}
}
#3.==============BeanFctory
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
/**
* Spring bean 工厂模式开发
* @author ghy
* @version 1.0
* @date 2021-12-28
**/
public class BeanFactory {
private static Map<String, Object> ioc = new HashMap<>();
private static Properties properties = new OrderedProperties();
static {
try {
properties.load(BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties"));
//beanNames : 是无序的
Set<String> beanNames = properties.stringPropertyNames();
for (String beanName : beanNames) {
if(null != beanName && !beanName.trim().equals("")) {
Class<?> clazz = Class.forName(properties.getProperty(beanName));
if(null != clazz) {
Object instance = clazz.newInstance();
if(null != instance) {
ioc.put(beanName, instance);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static Object getBean(String beanName){
return ioc.get(beanName);
}
}
标签:properties,java,spring,beanName,工厂,util,bean,import,public 来源: https://www.cnblogs.com/cqwiu/p/16317488.html