Spring介绍
- The Spring Framework provides a comprehensive programming and configuration model for modern Java-based enterprise applications - on any kind of deployment platform.
- A key element of Spring is infrastructural support at the application level: Spring focuses on the “plumbing” of enterprise applications so that teams can focus on application-level business logic, without unnecessary ties to specific deployment environments.
- 前面这么大一坨浓缩下来就是,spring提供基础设施支持,不用与特定的部署环境绑定。
- spring核心技术主要是IOC、AOP
IOC
inverse of control 即控制反转,就是将你设计好的类交给系统控制,不由你自己在内部控制。
DI(依赖注入)是实现IOC的一种方式
上图可以帮助我们理解,左图是自己控制类的调度,右图是spring容器控制调度,你需要什么他就给你什么,如果没有就抛异常。两则最直观的区别就是,前者自己控制对象,后者由spring容器控制对象,这就是控制反转。
代码举例
public class LoginController {
//这个属性没有被实例化
private LoginService loginService;
public String login(String username, String password){
String result= loginService.login(username,password);
return result;
}
public void setLoginService(LoginService loginService) {
this.loginService = loginService;
}
}
public interface LoginService {
public String login(String username,String password);
}
public class LoginServiceImpl implements LoginService {
private UserDAO userDAO;
@Override
public String login(String username, String password) {
User user=userDAO.findByuser(username,password);
return user!=null?"成功":"失败";
}
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
}
public interface UserDAO {
public User findByuser(String username,String password);
}
public class UserDAOImpl implements UserDAO {
@Override
public User findByuser(String username, String password) {
System.out.println(username+password);
return new User(username,password);
}
}
在idea中maven创建的项目的resources下的xml配置文件
<?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.ldl.etc.DAO.Impl.UserDAOImpl"></bean>
<bean id="LoginService" class="com.ldl.etc.service.impl.LoginServiceImpl">
<property name="userDAO" ref="UserDAO"></property>
</bean>
<bean id="LoginController" class="com.ldl.etc.controller.LoginController">
<property name="LoginService" ref="LoginService"></property>
</bean>
</beans>