实现要求:
在该实践案例中,使用注解的方式,完成模拟用户的正常登录。
要求如下: 使用注解方式开发模拟用户的正常登录。
实现思路:
在applicationContext.xml配置文件中开启注解扫描功能。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" 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-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd "> <!-- 开启注解扫描功能扫描com.mhys.pojo包以及子包中的类--> <context:component-scan base-package="pojo,dao,service"></context:component-scan> </beans>
在com.mhys.demo.pojo包下创建User类。
package pojo; public class User { private String username; private String 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; } @Override public String toString() { return "User [username=" + username + ", password=" + password + "]"; } }
在com.mhys.demo.dao包下创建UserDao类,使用@Component注册到容器,声明loginUser()方法。
package service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import dao.UserDao; import pojo.User; @Component public class UserService { @Autowired private UserDao userDao; public boolean loginUser(User user) { boolean flag=userDao.loginUser(user); return flag; } }
在com.mhys.demo.service包下创建UserService类,使用@Component注册到容器;然后使用@AutoWired注入属性;最后声明loginUser()方法。
package dao; import org.springframework.stereotype.Component; import pojo.User; @Component public class UserDao { public boolean loginUser(User user) { System.out.println("用户:"+ user.getUsername()+"登录成功! 密码:" +user.getPassword()+ "正确!"); return true; } }
在com.mhys.demo.test包下创建测试类。
package test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import pojo.User; import service.UserService; public class Test { 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); } }