Spring IOC/DI

Spring核心 IoC/DI

IoC/DI:Inversion of Control,控制反转 ,Dependency Injection 依赖注入
   传统的java开发模式中,当我们需要一个对象时,我们自己创建一个对象出来,而在Spring中,一切都有Spring容器使用了工厂模式为我们创建管理需要的对象。
AOP:Aspect Oriented Programming 面向切面
   AOP是Aspect Oriented Programming的缩写,意思是面向方面编程,而在面向切面编程中,我们将一个对象某些类似的方面横向抽象成一个切面,对这个切面进行一些如权限验证,事物管理,记录日志等操作。

Bean装配与实例化

BeanFactory和ApplicationContext就是spring框架的两个IOC容器,现在一般使用ApplicationnContext,其不但包含了BeanFactory的作用,同时还进行更多的扩展。(官网文档解释)。

The org.springframework.beans and org.springframework.context packages are the basis for Spring Framework's IoC container. The BeanFactory interface provides an advanced configuration mechanism capable of managing any type of object. ApplicationContext is a sub-interface of BeanFactory. It adds easier integration with Spring's AOP features; message resource handling (for use in internationalization), event publication; and application-layer specific contexts such as the WebApplicationContext for use in web applications.

public interface IUserService {
    public void sayName();
}
public class UserServiceImpl implements IUserService {
    @Override
    public void sayName() {
         System.out.println("My name is Spring IOC");
    }
}
ApplicationContext contextClassPath = new ClassPathXmlApplicationContext("applicationContext.xml");
//ApplicationContext  contextFileSystem = new FileSystemXmlApplicationContext("WebRoot/WEB-INF/applicationContext.xml");
UserServiceImpl userImpl = (UserServiceImpl) contextClassPath.getBean(UserServiceImpl.class);
userImpl.sayName();

实例化Spring IOC容器的简单方法(JDK5+ 支持泛型)
1.ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"spring配置文件路径"}); 
2.(已废弃)
Resource res = new FileSystemResource("spring配置文件");
BeanFactory factory = new XMLBeanFactory(res);
3.ApplicationContext  contextFileSystem = new FileSystemXmlApplicationContext(new String[]{"spring配置文件路径"});

Bean的XML配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <bean id="userservice" class="cn.base.web.service.impl.UserServiceImpl"></bean>
</beans>

1.一个Bean对应一个id,如果spring配置文件中有两个以上相同的id时,spring会报错。
2.一个Bean也可以通过一个name属性来引用和指定,如果spring配置文件中有两个以上相同name的Bean,则spring通过name引用时会自动覆盖前面相同name的bean引用。
很多时候,由于Spring需要管理和配置的东西比较多,我们可以根据模块分解开,过<import>元素将要引入的spring其他配置文件,如
 <import resource=”spring-service.xml”/>

依赖注入几种方式

原文地址:https://www.cnblogs.com/Irving/p/3308419.html