IoC/DI:Inversion of Control,控制反转 ,Dependency Injection 依赖注入
传统的java开发模式中,当咱们须要一个对象时,咱们本身建立一个对象出来,而在Spring中,一切都有Spring容器使用了工厂模式为咱们建立管理须要的对象。
AOP:Aspect Oriented Programming 面向切面
AOP是Aspect Oriented Programming的缩写,意思是面向方面编程,而在面向切面编程中,咱们将一个对象某些相似的方面横向抽象成一个切面,对这个切面进行一些如权限验证,事物管理,记录日志等操做。html
BeanFactory和ApplicationContext就是spring框架的两个IOC容器,如今通常使用ApplicationnContext,其不但包含了BeanFactory的做用,同时还进行更多的扩展。(官网文档解释)。java
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.web
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配置文件路径"});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”/> api