实现要求:
使用Eclipse搭建的Spring开发环境,属性注入通过构造方法方式实现,模拟用户的正常登录。要求如下:
通过构造方法实现属性注入。
控制台输出用户名和密码。
实现思路:
在com.mhys.demo.entity包下,创建User类,添加username和password两个属性。
package com.mhys.bean; public class User { private String username; private String password; public User() { super(); } public User(String username, String password) { super(); this.username = username; this.password = password; } @Override public String toString() { return "User [username=" + username + ", password=" + password + "]"; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
在com.mhys.demo.dao包下,创建UserDao类,声明loginUser()方法。
package com.mhys.Dao; import com.mhys.bean.User; public class UserDao { public boolean loginUser(User user) { System.out.println("用户:"+user.getUsername()+"登录成功!密码:"+user.getPassword()+"正确"); return true; } }
在com.mhys.demo.service包下,创建UserService类。
package com.mhys.Dao; import com.mhys.bean.User; public class UserService { private UserDao userDao; public UserService(UserDao userDao) { super(); this.userDao = userDao; } public UserService() { super(); } public boolean loginUser(User user) { boolean flag = userDao.loginUser(user); return flag; } }
在applicationContext.xml配置文件中,注册userDao类和userService类到容器。
<bean id="userDao" class="com.mhys.Dao.UserDao"></bean> <bean id="userService" class="com.mhys.Dao.UserService"> <constructor-arg name="userDao" ref="userDao"></constructor-arg> </bean>
在com.mhys.demo.test包下,创建测试类。
package com.mhys.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.mhys.Dao.UserService; import com.mhys.bean.User; public class T1_3_4Test { public static void main(String[] args) { // 获取上下文 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); UserService userService = (UserService)context.getBean("userService"); User user = new User(); user.setUsername("杨明金"); user.setPassword("123456"); userService.loginUser(user); } }