简单模拟了下依赖注入,直接上代码:
model.
User.java
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
dao
UserDao.java
public interface UserDao {
public void save();
}
daoimpl
UserDAOImpl .java
public class UserDAOImpl implements UserDao {
public void save() {
System.out.println("a user saved");
}
}
service
UserService .java
public class UserService {
private UserDao userDAO ;//=new UserDAOImpl();
public UserDao getUserDAO() {
return userDAO;
}
public void setUserDAO(UserDao userDAO) {
this.userDAO = userDAO;
}
public void add(User u) {
this.userDAO.save();
}
}
public class UserServiceTest {
@Test
public void testAdd() throws Exception, IOException,
InstantiationException, IllegalAccessException,
ClassNotFoundException {
BeanFactory factory = new ClassPathXmlApplicationContext();
UserService service = (UserService) factory.getBean("userService");
User u = new User();
service.add(u);
}
}
spring'
public interface BeanFactory {
public Object getBean(String name);
}
public class ClassPathXmlApplicationContext implements BeanFactory {
private Map<String, Object> beans = new HashMap<String, Object>();
public ClassPathXmlApplicationContext() throws JDOMException, IOException,
InstantiationException, IllegalAccessException,
ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(this.getClass().getClassLoader()
.getResourceAsStream("beans.xml"));
Element root = doc.getRootElement();
List list = root.getChildren("bean");
for (int i = 0; i < list.size(); i++) {
Element element = (Element) list.get(i);
String id = element.getAttributeValue("id");
String clazz = element.getAttributeValue("class");
System.out.println(id + ":" + clazz);
Object obj = Class.forName(clazz).newInstance();
beans.put(id, obj);
for (Element propertyElement : (List<Element>) element
.getChildren("property")) {
String name = propertyElement.getAttributeValue("name");//userDAO
String bean = propertyElement.getAttributeValue("bean");//u
Object beanObject = beans.get(bean);
String methodName = "set" + name.substring(0, 1).toUpperCase()
+ name.substring(1);
System.out.println("method name = " + methodName);
Method m = obj.getClass().getMethod(methodName,
beanObject.getClass().getInterfaces()[0]);
m.invoke(obj, beanObject);
}
}
}
public Object getBean(String name) {
return beans.get(name);
}
}
beans.xml
<beans>
<bean id="u" class="com.cjw.dao.impl.UserDAOImpl" />
<bean id="userService" class="com.cjw.service.UserService" >
<property name="userDAO" bean="u"/>
</bean>
</beans>