Spring 入門-01-依賴注入
1.新增jar包
需要到下載好的spring裡的libs尋找基礎的四個包,beans,context,core,expression(或許有別的更方便的方法),還有第三方依賴包commons-logging
2.建立applicationContext.xml檔案,寫好框架,
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
">(這個根據情況需要寫的內容不同,不知道有什麼方法可以更方便得寫這些資訊,沒在Libraries裡找到模板)
</beans>
3.編寫UserDao介面和其實現類UserDaoImpl
public interface UserDao {
public void save();
}
public class UserDaoImpl implements UserDao {
@Override
public void save() {
// TODO Auto-generated method stub
System.out.println("call save method");
}
}
4.編寫UserService介面和其實現類UserServiceImpl
public interface UserService {
public void addUser();
}
public class UserServiceImpl implements UserService {
private UserDao userdao;
//用於給Spring容器進行依賴注入的方法(setter注入方式)
public void setUserDao(UserDao userdao) {
this.userdao = userdao;
}
@Override
public void addUser() {
// TODO Auto-generated method stub
this.userdao.save();
System.out.println("call addUser method");
}
}
5.在applicationContext裡進行配置
<bean id="userDao" class="book.c12.ioc.UserDaoImpl"></bean>
<bean id="userService" class="book.c12.ioc.UserServiceImpl">
<property name="userDao" ref="userDao" />
</bean>
6.編寫測試類
public class TestApp {
public void demo01(){
String xmlPath="applicationContext.xml";
ApplicationContext applicationContext=new ClassPathXmlApplicationContext(xmlPath);
UserDao userDao=(UserDao)applicationContext.getBean("userDao");
userDao.save();
}
@Test
public void demo02(){
String xmlPath="applicationContext.xml";
ApplicationContext applicationContext=new ClassPathXmlApplicationContext(xmlPath);
UserService userService=(UserService)applicationContext.getBean("userService");
userService.addUser();
}
}
執行,結果:
xml檔案找不到,原因是String xmlPath="applicationContext.xml";此句裡的applicationContext拼錯,寫成了appliactionContext
修改後,
userDao沒能被注入,原因: public void setUserDao(UserDao userdao)寫成了public void setUserdao(UserDao userdao)
修改後,執行成功。