下面以属性setter方法注入为例,实现一个简单的登录验证。具体实现步骤如下所示。
(1)编写DAO层:在项目的com.lq包下新建dao包,在dao包下创建接口UserDao.java,在UserDao.java接口中添加方法login(),用于实现登录功能。
package com.lq.dao;/*** @Author: Luqing Teacher* @CreateTime: 2024-11-29* @Description: 接口类UserDao实现* @Version: 1.0*/public interface UserDao {public boolean login(String name, String pwd);
}
(2)编写DAO层的实现类:在com.lq.dao包下创建impl包,在impl包下创建UserDao接口的实现类UserDaoImpl,在UserDaoImpl类中实现login()方法。
package com.lq.dao.impl;import com.lq.dao.UserDao;/*** @Author: Luqing Teacher* @CreateTime: 2024-11-29* @Description: UserDaoImpl 接口实现类* @Version: 1.0*/public class UserDaoImpl implements UserDao {@Overridepublic boolean login(String name, String pwd) {if (name.equals("张三") && pwd.equals("123")){return true;}return false;}
}
(3)编写Service层:在项目的com.lq包下新建service包,在service包下创建接口UserService.java,在接口中添加方法login()。
package com.lq.service;/*** @Author: lzq* @CreateTime: 2024-11-29* @Description: UserService服务接口类* @Version: 1.0*/public interface UserService {public boolean login(String name, String pwd);
}
(4)编写Service层实现类:在com.lq.service包下创建impl包,在impl包下创建UserService接口的实现类UserServiceImpl,在UserServiceImpl类中实现login()方法。
package com.lq.service.impl;import com.lq.dao.UserDao;
import com.lq.service.UserService;/*** @Author: Luqing Teacher* @CreateTime: 2024-11-29* @Description: UserServiceImpl实现类* @Version: 1.0*/public class UserServiceImpl implements UserService {UserDao userDao;public void setUserDao(UserDao userDao) {this.userDao = userDao;}@Overridepublic boolean login(String name, String pwd) {return userDao.login(name, pwd);}
}
(5)编写applicationContext-login.xml配置文件:使用<bean>元素添加创建的UserDaoImpl类和UserServiceImpl类的实例,并配置其相关属性。
<?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"><bean id="userDao" class="com.lq.dao.impl.UserDaoImpl"/><bean id="userService" class="com.lq.service.impl.UserServiceImpl"><property name="userDao" ref="userDao"/></bean></beans>
(6) 编写测试类:在com.lq的测试包中新建测试类TestLogin。
package com.lq.test;import com.lq.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;/*** @Author: Luqing Teacher* @CreateTime: 2024-11-29* @Description: TestLogin测试登陆验证* @Version: 1.0*/public class TestLogin{public static void main(String[] args) {ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext-login.xml");UserService userService = (UserService) applicationContext.getBean("userService");boolean flag = userService.login("admin", "123");if (flag){System.out.println("登陆成功");}else {System.out.println("登陆失败");}}
}
运行结果如下: