1. 程式人生 > 其它 >spring bean工廠模式

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);
}

}