1. 程式人生 > >四、Spring與Dao練手小案例

四、Spring與Dao練手小案例

1.分析

  • 程式碼分為三層,分別為dao、service和test(測試用,暫時不涉及web)。
  • 每個類擁有自己的介面和實現類。

2.Dao

  • 包名是com.itlike.dao
  • UserDao(介面)
package com.itlike.dao;
public interface UserDao {
    public void delete();
}
  • UserDaoImpl(實現類)
package com.itlike.dao;
import org.springframework.stereotype.
Repository; @Repository("userDao") public class UserDaoImpl implements UserDao{ @Override public void delete(){ System.out.println("從資料庫當中刪除記錄"); } }

3.Service

  • 包名是com.itlike.service
  • UserService(介面)
package com.itlike.service;
public interface UserService {
    public
void delete(); }
  • UserServiceImpl(實現類)
package com.itlike.service;
import com.itlike.dao.UserDao;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service("userService")
public class UserServiceImpl implements UserService {
    @Resource(name="userDao")
    private
UserDao userDao; @Override public void delete() { userDao.delete(); } }

4.Test

  • 包名是com.itlike.test
  • UserTest
package com.itlike.test;

import com.itlike.service.UserService;
import com.itlike.service.UserServiceImpl;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class UserTest {
    @Test
    public void test(){
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService user =(UserServiceImpl) app.getBean("userService");
        user.delete(); //從資料庫當中刪除記錄
    }
}

輸出:從資料庫當中刪除記錄

5.相關配置檔案

  • 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"
       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="com.itlike"/>
</beans>
  • log4j.properties
# Define the root logger with appender file
log4j.rootLogger = DEBUG, FILE

# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
# Set the name of the file
log4j.appender.FILE.File=D://mylog.log

# Set the immediate flush to true (default)
log4j.appender.FILE.ImmediateFlush=true

# Set the threshold to debug mode
log4j.appender.FILE.Threshold=debug

# Set the append to false, overwrite
log4j.appender.FILE.Append=false

# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n