Spring
主要作用:spring的主要作用是解耦,降低代码间的耦合度(指降低类和类之间的耦合度)。根据功能的不同,可以将系统中的代码分成主业务逻辑和系统级业务逻辑两类。Spring根据代码功能的特点,降低耦合度的方式分为两类:Ioc(控制反转)和AOP(面向切面编程)至于这两种方式的具体解释后面再说,或者自己查。Spring是一个容器,
1.1Spring与IOC
1.1.1bean的装配(上代码)
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--注册service对象,通过动态工厂生成service对象,然后直接通过配置文件将改对象放入Spring的Bean容器中,这里的init-method, destroy-method是两个方法在某个类中-->
<bean id="someService1" class="com.ba04.SomeServiceImp" init-method="initAfter" destroy-method="descory"></bean>
<!--bean后处理器-->
<bean class="com.ba04.MyBeanPost"></bean>
</beans>
@Test //Junit调试
public void mytest02() {
//加载spring配置文件,创建spring容器对象,在执行配置文件时,配置文件中添加的对象都会被创建出来,
ApplicationContext ac= new ClassPathXmlApplicationContext("com/ba04/applicationContext.xml");
//获取需要的对象
ISomeService service1 =(ISomeService) ac.getBean("someService1");
String name=service1.doFirst();
service1.dosercend();
System.out.println(name);
System.out.println("-----------------------------");
((ClassPathXmlApplicationContext)ac).close();
}
1.1.2 bean工厂(静态工厂和动态工厂)这里只放了两个关键代码,静态工厂加个static关键字,然后因为是静态可以直接获取所以在注释里
//动态工厂,
public class ServiceFactory {
public ISomeService getSomeService() {
return new SomeServiceImp();
}
}
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--注册service对象,通过动态工厂生成service对象,然后直接通过配置文件将改对象放入Spring的Bean容器中-->
<!--scope="prototype" 原型模式:真正使用时才创建,每获取一次都会创建不同的对象 -->
<!--(默认)scope="singleton" 单例模式:容器初始化时就创建,每次获取的都是同一个对象 -->
<bean id="serviceFactory" class="com.ba01.ServiceFactory" />
<!-- bean 中油专门的方法可以通过他直接用动态工厂中的方法来获取需要的对象 -->
<!--<bean id="someService" class="com.ba02.ServiceFactory" factory-method="getSomeService"></bean>-->
<bean id="someService" factory-bean="serviceFactory" factory-method="getSomeService"></bean>
</beans>