day2.1.4spring ioc实现登录功能
程序员文章站
2022-07-12 12:57:22
...
Spring 介绍
Spring 是分层的 Java SE/EE 应用 full-stack 轻量级开源框架
-
full-stack:servlet service dao
-
轻量级: 按需添加模块
-
开源:可以获取源代码
以 IoC- (Inverse Of Control:反转控制)和 AOP- (Aspect Oriented Programming:面向切面编程)
为内核
SpringIOC介绍:
类似于c内存分配和回收由程序员管理,java将这个过程通过jvm进行管理,程序员将主要精力用于业务逻辑的处理。程序员传统创建对象通过new来完成,而现在程序员只要在配置文件写少量代码就行,对象的创建和管理由spring来完成。
IDEA+Spring开发环境搭建:
maven导入依赖
<dependencies>
<!--spring依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<!--日志包-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
开发步骤:
TestLoginService:
public class TestLoginService {
private static final Logger logger = LoggerFactory.getLogger(TestLoginService.class);
private ClassPathXmlApplicationContext context;
@Before
public void init(){
//1:创建ioc 容器对象 暂时看成map
context=new ClassPathXmlApplicationContext("applicationContext.xml");
//2:给定配置文件的名称 applicationContext.xml
}
@Test
public void Test01(){
LoginService loginService = (LoginService) context.getBean("loginService");
User user = (User) context.getBean("user");
user.setUsername("jack");
user.setPassword("123456");
logger.debug(user+"");
int res = loginService.login(user);
if(res == -1){
System.out.println("用户不存在");
}else if(res == 1){
System.out.println("登录成功");
}else{
System.out.println("密码错误");
}
logger.debug(loginService+":res="+res);
}
}
LoginService:
@Service
public class LoginService {
@Autowired
@Qualifier("loginDao")
private LoginDao loginDao;
public int login(User user) {
User u = loginDao.login(user);
if (u == null) {
return -1;
} else if (u.getUsername().equals(user.getUsername()) && u.getPassword().equals(user.getPassword())){
return 1;
}else {
return -2;
}
}
}
LoginDao:
@Repository
public class LoginDao {
private User u;
{
u = new User();
u.setUsername("jack");
u.setPassword("123456");
}
public User login(User user) {
return u;
}
}
User:
@Component
public class User {
private String username;
private String password;
public User() {
}
public User(String username, String password) {
this.username = username;
this.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;
}
// @Override
// public String toString() {
// return "User{" +
// "username='" + username + '\'' +
// ", password='" + password + '\'' +
// '}';
// }
}
运行结果:
上一篇: Spring IOC的简单实现
下一篇: Spring学习-装配Bean