IDao.java
package com.wh.IDao; public interface IDao { boolean insert(); }
OracleDaoImpl.java
package com.wh.dao; import org.springframework.stereotype.Repository; import com.wh.IDao.IDao; @Repository public class OracleDaoImpl implements IDao{ @Override public boolean insert() { return true; } }
MySQLDaoImpl.java
package com.wh.dao; import com.wh.IDao.IDao; public class MySQLDaoImpl implements IDao { @Override public boolean insert() { return true; } }
UserService.java
package com.wh.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.wh.dao.OracleDaoImpl; @Service public class UserService { @Resource(name="mySqlDaoImpl") //@Autowired只适合不是多态的实现,单个类(自动注解) private IDao dao;//若属性是接口,且有多个子类实现该接口时,建议使用@Resource(name="xxx")比较好,实现多态的效果 public boolean insert() { return dao.insert(); } public OracleDaoImpl getDao() { return dao; } public void setDao(OracleDaoImpl dao) { this.dao = dao; } }
UserController.java
package com.wh.control; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.wh.service.UserService; @Controller public class UserController { @Autowired private UserService us; public boolean requestInsert(){ return us.insert(); } public UserService getUs() { return us; } public void setUs(UserService us) { this.us = us; } }
TestMVC.java
package com.wh.test; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.wh.bean.Student; import com.wh.control.UserController; public class TestMVC { @Test public void testUser2(){ ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); UserController c =(UserController)ac.getBean("userController"); System.out.println(c); } }
applicationContext.xml
package com.wh.test; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.wh.bean.Student; import com.wh.control.UserController; public class TestMVC { @Test public void testUser2(){ ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); UserController c =(UserController)ac.getBean("userController"); System.out.println(c); } }
时间: 2024-10-10 17:14:35