IDEA开发的简单“登陆成功”小项目
IDEA项目结构:
每一部分代码和相应的解读:
com.itTony文件下有dao(实体)层,service(服务)层,编写的2个类(HelloSpring和TestSpring)和applicationContext.xml
package com.itTony;
public class HelloSpring {
private String userName;
public void setUserName(String userName) {
this.userName = userName;
}
public void show() {
System.out.println(userName + ":欢迎来到Spring");
}
}
package com.itTony;
import com.itTony.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpring {
public static void main(String[] args) {
//加载applicationContext.xml配置
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("applicationContext.xml");
//获取配置中的UserService实例
UserService userService = (UserService)
applicationContext.getBean("userService");
boolean flag = userService.login("张三", "123");
if (flag) {
System.out.println("登录成功");
} else {
System.out.println("登录失败");
}
}
}
<?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">
<!-- 将指定类配置给Spring,让Spring创建HelloSpring对象的实例 -->
<bean id="helloSpring" class="com.itTony.HelloSpring">
<!--为userName属性赋值-->
<property name="userName" value="张三"></property>
</bean>
<bean id="userDao" class="com.itTony.dao.impl.UserDaoImpl"></bean>
<bean id="userService" class="com.itTony.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
</beans>
在dao层写了个接口(UserDao),对用户名和密码进行bool值的判断。
package com.itTony.dao;
public interface UserDao {
boolean login(String username, String password);
}
在dao目录下写了个impl包,UserDaoImpl实现了UserDao。
package com.itTony.dao.impl;
import com.itTony.dao.UserDao;
public class UserDaoImpl implements UserDao {
@Override
public boolean login(String name, String password) {
return name.equals("张三") && password.equals("123");
}
}
service层与dao层的结构类似。
package com.itTony.service;
public interface UserService {
boolean login(String username, String password);
}
package com.itTony.service.impl;
import com.itTony.dao.UserDao;
import com.itTony.service.UserService;
public class UserServiceImpl implements UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public boolean login(String name, String password) {
return userDao.login(name, password);
}
}
测试结果:因为用户名和密码匹配成功。所以显示登录成功。
jar包的管理:
小结:项目虽小,但是让我体会到了spring核心容器的功能,加深了对它的概念的理解和认识。以及项目编写的一些基本逻辑和结构,对jar包是手动管理的,后面会陆续学习用maven进行jar包管理的,使得开发更加的高效和便捷。