spring註解1
阿新 • • 發佈:2017-05-07
XML itcast autowire spa cast encoding ans 測試 目錄
1. src下目錄結構如下:
2.測試類
public class App { // 創建容器對象 private ApplicationContext ac = new ClassPathXmlApplicationContext("cn/itcast/e_anno/bean.xml"); @Test public void testExecuteAction() { // 從容器中獲取Action UserAction userAction = (UserAction) ac.getBean("userAction"); userAction.execute(); } }
3.控制層
@Controller // 加入IOC容器 public class UserAction { @Autowired private UserService userService; public String execute() { userService.save(); return null; } }
4.業務邏輯層
@Service // userService加入ioc容器 public class UserService { @Autowired private UserDao userDao; public void save() { userDao.save(); } }
5.持久層
@Repository // 相當於bean.xml 【<bean id=userDao class=".." />】 public class UserDao { public void save() { System.out.println("DB:保存用戶!!!"); } }
6. spring的配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 開啟註解掃描 --> <context:component-scan base-package="cn.itcast.e_anno"></context:component-scan> </beans>
spring註解1