Spring的IoC与DI
现在学习基于Servlet技术开发SpringMVC框架。在学习SpringMVC之前要先了解Spring框架。
想要了解Spring,就要从 Spring是什么、Spring能做什么、用Spring有什么好处、Spring该怎么使用 这个几个方面入手。
个人参考的是开涛大神
的跟我学Spring
系列文章。
Spring是什么
Spring是JavaEE的开源框架,其通过实现IoC/DI进行容器管理,简化企业级应用程序开发,管理了各个模块的依赖。
IoC (Inversion of Control)控制反转。这里要明白谁控制谁,什么是反转。
public class User{
private UserInfo userInfo;
public getUserName(){
return userInfo.name;
}
}
在上面的代码中,有个getUserName方法,该方法需要用户信息中的名称。如果没有UserInfo实例程序会产生错误。此刻 User 依赖 UserInfo,UserInfo 控制了 User。想要正常使用User必须手动构建UserInfo再赋值给User。
基于IoC的理念,User、UserInfo均由类管理容器创建,如果检测到User 依赖 UserInfo 则赋值给 User。示例如下:
public class IoCBeanFactory{
public static Map<String, Object> beans = new HashMap();
public void init(){
beanLoad();
}
public void beanLoad(){
beans.put("user", new User());
beans.put("userInfo", new UserInfo());
}
public void dependencyInjection(){
//检查到User依赖UserInfo
User u = (User)beans.get("user");
//设置属性
UserInfo uinfo = (UserInfo)beans.get("userInfo");
u.setUserInfo(uinfo);
}
}
通过IoCBeanFactory 获取的User则无需担心 userInfo 的问题了。这便是控制反转,反转了由依赖方 构建 被依赖方的实例。由该类创建的实例,检查实例的属性依赖并设置对应的属性,就是DI(dependency injection)理念的实现。
Spring能做什么
Spring 除了对bean的管理之外,还可以通过AOP切面管理Bean、对数据库进行操作的JDBC、整合了常见的持久化层ORM、还有实现了MVC的weib管理器
用Spring有什么好处,该怎么使用
以一个Demo来说
添加application.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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="hello" class="yongy.javaspring.service.impl.HelloWorldImpl"></bean>
</beans>
通过简单的xml配置,就能添加一个bean到ioc容器中,在需要的时候只需getBean就能获取到实例,减少了手动构建实例。
public interface HelloWorld {
void sayHello();
}
public class HelloWorldImpl implements HelloWorld {
@Override
public void sayHello() {
System.out.println("HelloWorld!");
}
}
public class JavaSpringApplicationTest {
@Test
public void helloWorld(){
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
HelloWorld hello = context.getBean("hello", HelloWorld.class);
hello.sayHello();
}
}