Spring_1

 Spring入门篇-IMOOC

此classpath,在工程中配置,project->property-java build path/source folder add

RESOURCE:

http://spring.io/

http://projects.spring.io/spring-framework/

2017/03/20

1.所有Spring管理的对象都是bean

===============================================

接口:用于沟通的中介勿的抽象化。

  实体把自己提供给外界的一种抽象化说明,用以由内部操作分离出外部沟通方法,使其能被修改内部而不影响外界其他实体与其交互的方式

  对应Java接口即声明,声明了那些方法是对外公开提供的

  Java8中,接口可以拥有方法体

面向接口编程Interface oriented programming:

  结构设计中,分清层次及调用关系,每层只向外(上层)提供一组功能结构,各层间仅依靠接口而非实现类

  接口实现的变动不影响各层间的调用,这点在公共服务中尤其重要

  “面向接口编程”中的“接口”是用于隐藏具体实现和实现多态性的组件

  例子:

===IOC===================================

 

IOC:Inversion of Control的缩写,多数书籍翻译成“控制反转”,还有些书籍翻译成为“控制反向”或者“控制倒置”。

IOC的别名:依赖注入(DI:Dependeny Injection)
  2004年,Martin Fowler探讨了同一个问题,既然IOC是控制反转,那么到底是“哪些方面的控制被反转了呢?”,经过详细地分析和论证后,他得出了答案:“获得依赖对象的过程被反转了”。控制被反转之后,获得依赖对象的过程由自身管理变为了由IOC容器主动注入。于是,他给“控制反转”取了一个更合适的名字叫做“依赖注入(Dependency Injection)”。他的这个答案,实际上给出了实现IOC的方法:注入。所谓依赖注入,就是由IOC容器在运行期间,动态地将某种依赖关系注入到对象之中。

  所以,依赖注入(DI)和控制反转(IOC)是从不同的角度的描述的同一件事情,就是指通过引入IOC容器,利用依赖关系注入的方式,实现对象之间的解耦。

IOC:

  .找IOC容器

  .容器返回对象

  .使用对象

IOC容器中,所有对象都是Bean.

Spring对Bean的管理有两种方式:

  1)XML配置 (本课着重描述)

  2)注解

-------------------------------------------

Spring的Bean配置(XML)

1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
6 xsi:schemaLocation="http://www.springframework.org/schema/beans 

   http://www.springframework.org/schema/beans/spring-beans.xsd


9     <!-- 配置bean

10 class:bean的全类名,通过反射的方式在IOC容器中创建Bean,所以要求Bean中必须有无参数的构造器

11 id:标识容器中的bean,id唯一。

12     -->
13     <bean id="helloSpring" class="com.yl.HelloSpring">
14         <property name="name" value="Spring"></property>
15     </bean>

</beans>

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xsi:schemaLocation="http://www.springframework.org/schema/beans
 5         http://www.springframework.org/schema/beans/spring-beans.xsd">
 6         <bean id = "springTest" class="com.imooc.spring.ioc.HelloSpringIoc">
 7             <property name="name" value="spring"></property>
 8         </bean>
 9         <bean id = "oneInterface" class="com.imooc.interfacecodeing.OneInterfaceImp">
10         </bean>
11 </beans>

 ------Junit 单元测试--------------------------------------------------

1·下载Junit-*.jar并引入工程

2·创建UnitTestBase类,完成对Spring配置文件的加载,销毁

3·所有的单元测试类都继承自UnitTestBase,通过它的getBean()方法获得想要的对象。

4·子类(具体执行单元测试的类)加注解:

  @RunWith(BlockJUnit4ClassRunner.class)

5·单元测试方法的加注解:@Test

6·右键选择要执行的单元测试方法执行或者执行一个类的全部单元测试方法

1·UnitTestBase类

package com.imooc.test;

import org.junit.After;
import org.junit.Before;
import org.springframework.beans.BeansException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.StringUtils;

public class UnitTestBase {
    private ClassPathXmlApplicationContext context;
    private String springXmlpath;
    
    public UnitTestBase(){}
    
    public UnitTestBase(String springXmlpath){
        this.springXmlpath = springXmlpath;
    }
    
    @Before
    public void before(){
        if(StringUtils.isEmpty(springXmlpath)){
            springXmlpath = "classpath*:spring-*.xml";
        }
        try{
            context = new ClassPathXmlApplicationContext(springXmlpath);
            context.start();
            
        }catch (BeansException e){
            e.printStackTrace();
        }

    }
    
    @After
    public void after(){
        context.destroy();
    }
    
    @SuppressWarnings("unchecked")
    protected <T extends Object> T getBean(String beanId) {
      try {
       return (T)context.getBean(beanId);
      } catch (BeansException e) {
       e.printStackTrace();
       return null;
      }
    }
         
    protected <T extends Object> T getBean(Class<T> clazz) {
      try {
       return context.getBean(clazz);
      } catch (BeansException e) {
       e.printStackTrace();
       return null;
      }
    }
}

package com.imooc.test.base;

import org.junit.After;
import org.junit.Before;
import org.springframework.beans.BeansException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.StringUtils;

public class UnitTestBase {
 
 private ClassPathXmlApplicationContext context;
 
 private String springXmlpath;
 
 public UnitTestBase() {}
 
 public UnitTestBase(String springXmlpath) {
  this.springXmlpath = springXmlpath;
 }
 
 @Before
 public void before() {
  if (StringUtils.isEmpty(springXmlpath)) {
   springXmlpath = "classpath*:spring-*.xml";//此classpath,在工程中配置,project->property-java build path/source folder add
  }
  try {
   context = new ClassPathXmlApplicationContext(springXmlpath.split("[,\s]+"));//JAVA豆知识 [22]---20171207 //s 参照
   context.start();
  } catch (BeansException e) {
   e.printStackTrace();
  }
 }
 
 @After
 public void after() {
  context.destroy();
 }
 
 @SuppressWarnings("unchecked")
 protected <T extends Object> T getBean(String beanId) {
  try {
   return (T)context.getBean(beanId);
  } catch (BeansException e) {
   e.printStackTrace();
   return null;
  }
 }
 
 protected <T extends Object> T getBean(Class<T> clazz) {
  try {
   return context.getBean(clazz);
  } catch (BeansException e) {
   e.printStackTrace();
   return null;
  }
 }

}

4·子类(具体执行单元测试的类)加注解:

 1 package com.imooc.spring.ioc;
 2 
 3 import org.junit.Test;
 4 import org.junit.runner.RunWith;
 5 import org.junit.runners.BlockJUnit4ClassRunner;
 6 
 7 import com.imooc.interfacecodeing.OneInterface;
 8 import com.imooc.test.UnitTestBase;
 9 
10 @RunWith(BlockJUnit4ClassRunner.class)
11 public class TestOneInterface extends UnitTestBase {
12     public TestOneInterface(){
13         super("classpath*:spring-ioc.xml");
14     }
15     @Test
16     public void testSay(){
17         OneInterface oneInterface = super.getBean("oneInterface");
18         HelloSpringIf hello = super.getBean("springTest");
19         System.out.println(oneInterface.say("  !!! this is a test of ioc!"));
20         hello.printOut();
21         
22     }
23 }

@RunWith(BlockJUnit4ClassRunner.class)
public class TestOneInterface extends UnitTestBase {

 public TestOneInterface() {
  super("classpath*:spring-ioc.xml");
 }
 
 @Test
 public void testSay() {
  OneInterface oneInterface = super.getBean("oneInterface");
  oneInterface.say("This is a test.");
 }

}

console:output

六月 02, 2017 11:18:33 上午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@3830f1c0: startup date [Fri Jun 02 11:18:33 CST 2017]; root of context hierarchy
六月 02, 2017 11:18:33 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from URL [file:/D:/java/workspace/com.imooc.study/bin/spring-ioc.xml]
the string of input:  !!! this is a test of ioc!
HelloSpringIoc.java printOut method:spring
六月 02, 2017 11:18:33 上午 org.springframework.context.support.AbstractApplicationContext doClose
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@3830f1c0: startup date [Fri Jun 02 11:18:33 CST 2017]; root of context hierarchy

---Bean容器初始化---------------------------------------------------------------------

基础:两个包

-org.springframework.beans
-org.springframework.context

-BeanFactory提供配置结构和基本功能,加载并初始化Bean

-ApplicationContext保存了Bean对象并在Spring中被广泛使用

方式:ApplicationContext

-本地文件:

  例子 FileSystemXmlApplicationContext context= new FileSystemXmlApplicationContext context("F:/workspace/appcontext.xml");

-Classpath

  例子:ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext context("classpath:spring-context.xml");

-Web应用中依赖servlet或者Listener

  Web 应用:

  <listener>

    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

  </listener>

      <servlet>

        <servlet-name>context</servlet-name>

        <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>

        <load-on-startup>1</load-on-startup>

      </servlet>

----------------------------------------------------------

Spring注入方式

Spring注入是指在启动Spring容器加载bean配置的时候,完成对变量的赋值行为

·常用的两种注入方式:

-设值注入

-构造注入

-设值注入:通过set的方式去注入

-构造注入

public interface InjectionService {
 
 public void save(String arg);
 
}
public class InjectionDAOImpl implements InjectionDAO {
 
 public void save(String arg) {
  //模拟数据库保存操作
  System.out.println("保存数据:" + arg);
 }

}
public class InjectionServiceImpl implements InjectionService {
 
 private InjectionDAO injectionDAO;
 
 //构造器注入
 public InjectionServiceImpl(InjectionDAO injectionDAO) {//参数名必须与配置文件一致injectionDAO
  this.injectionDAO = injectionDAO;
 }
 
 //设值注入:通过set方法
// public void setInjectionDAO(InjectionDAO injectionDAO) {
//  this.injectionDAO = injectionDAO;
// }

 public void save(String arg) {
  //模拟业务操作
  System.out.println("Service接收参数:" + arg);
  arg = arg + ":" + this.hashCode();
  injectionDAO.save(arg);
 }
 
}

※ーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーー

spring-injection.xml设值注入
 //设值注入:通过set方法
  public void setInjectionDAO(InjectionDAO injectionDAO) {
   this.injectionDAO = injectionDAO;
  }
 <bean id="injectionService" class="com.imooc.ioc.injection.service.InjectionServiceImpl">
         <property name="injectionDAO" ref="injectionDAO"></property>//name,InjectionServiceImpl中的属性名,ref为配置文件中的id名(下行)
        </bean>
 <bean id="injectionDAO" class="com.imooc.ioc.injection.dao.InjectionDAOImpl"></bean>
构造器注入
 <bean id="injectionService" class="com.imooc.ioc.injection.service.InjectionServiceImpl">
         <constructor-arg name="injectionDAO" ref="injectionDAO"></constructor-arg>//name,InjectionServiceImpl中的属性名,ref为配置文件中的id名(下行)
        </bean>
       
        <bean id="injectionDAO" class="com.imooc.ioc.injection.dao.InjectionDAOImpl"></bean>

※ーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーー

test:

@RunWith(BlockJUnit4ClassRunner.class)
public class TestInjection extends UnitTestBase {
 
 public TestInjection() {
  super("classpath:spring-injection.xml");
 }
 
 @Test
 public void testSetter() {
  InjectionService service = super.getBean("injectionService");
  service.save("这是要保存的数据");
 }
 
 @Test
 public void testCons() {
  InjectionService service = super.getBean("injectionService");
  service.save("这是要保存的数据");
 }
 
}

===Spring Bean装配之bean的配置===================================================
bean的配置项(常用)
Id:IOC容器中bean的唯一标识
Class具体实例化的类(理论上唯一的必须项)
Scope范围
Constructor arguments构造器参数
Properties属性
Autowiring mode自动装配
lazy-initialization mode懒加载模式
Initialization/destruction method初始化/销毁方法

Bean的作用域
·singleton:单例,指一个Bean容器中只存在一份
prototype:每次请求(每次使用)创建新的实例,destroy方式不生效
request:每次http请求创建一个实例且仅在当前request内有效
session:同上每次http请求创建,当前session内有效
global session:基于portlet的web中有效(portlet定义了global session),如果是在web中,同session
例子:singleton和prototype
spring-beanscope.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="beanScope" class="com.imooc.bean.BeanScope" scope="singleton"></bean>
       
 </beans>


 public TestBeanScope() {
  super("classpath*:spring-beanscope.xml");
 }
 
 @Test singleton  输出的hashcode一致和prototype输出的hashcode不同
 public void testSay() {
  BeanScope beanScope = super.getBean("beanScope");
  beanScope.say();
  
  BeanScope beanScope2 = super.getBean("beanScope");
  beanScope2.say();
 }
 
 @Test testSay()和testSay2()在用junit执行时,相当于两个容器,所以检验hashcode肯定会不同
 public void testSay2() {
  BeanScope beanScope  = super.getBean("beanScope");
  beanScope.say();
 }


public class BeanScope {
 
 public void say() {
  System.out.println("BeanScope say : " + this.hashCode());
 }
 
}
---Spring Bean装配之Bean的生命周期 ---------------------------------------------------------------------

生命周期:
·定义
·初始化
 方式1.-实现org.springframework.beans.factory.InitializingBean接口,覆盖afterPropertiesSet方法
 public class ExampleBean implements InitializingBean{
  @override
  public void afterPropertiesSet() throws Exception{
   //do some initialization work
  }
 
 }
 方式2.-配置init-method(必须实现)
 <bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"></bean>
 
 public class ExampleBean {
 
  public void init() {
   //do some initialization work
  }
 
 }
·使用
·销毁

 方式1.-实现org.springframework.beans.factory.DisposableBean接口,覆盖destory方法
 public class ExampleBean implements DisposableBean{
  @override
  public void destory() throws Exception{
   //do some destruction work(like releasing pooled connections)
  }
 
 }
 方式2.-配置destory-method(必须实现)
 <bean id="exampleInitBean" class="examples.ExampleBean" destory-method="clearup"></bean>
 
 public class ExampleBean {
 
  public void clearup() {
   //do some destruction work(like releasing pooled connections)
  }
 
 }

还有一种方式
·配置全局默认初始化,销毁方法(配置的方法没有实现时,也正常执行,所以属于可选方法(不必须实现))
<?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"
 default-init-method="init" default-destory-method="destory">
       
 </beans>
 
例子(生命周期,即初始化和销毁方法的例子)
注意:三种方式同时使用的时候优先顺序:
初始化:afterPropertiesSet->start 销毁destory->stop,接口先于配置法,而此时默认的全局初始化方法不执行。
<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"
        default-init-method="defautInit" default-destroy-method="defaultDestroy">
       
        <bean id="beanLifeCycle" class="com.imooc.lifecycle.BeanLifeCycle"  init-method="start" destroy-method="stop"></bean>
 
 </beans>

//public class BeanLifeCycle { //配置init-method,destroy-method
public class BeanLifeCycle implements InitializingBean, DisposableBean {//实现接口InitializingBean, DisposableBean 方式
 
 public void defautInit() {
  System.out.println("Bean defautInit.");
 }
 
 public void defaultDestroy() {
  System.out.println("Bean defaultDestroy.");
 }

 @Override
 public void destroy() throws Exception {
  System.out.println("Bean destroy.");
 }

 @Override
 public void afterPropertiesSet() throws Exception {
  System.out.println("Bean afterPropertiesSet.");
 }
 
 public void start() {
  System.out.println("Bean start .");
 }
 
 public void stop() {
  System.out.println("Bean stop.");
 }
 
}

@RunWith(BlockJUnit4ClassRunner.class)
public class TestBeanLifecycle extends UnitTestBase {
 
 public TestBeanLifecycle() {
  super("classpath:spring-lifecycle.xml");
 }
 
 @Test
 public void test1() {
  super.getBean("beanLifeCycle");
 }
 
}

2017-12-09 09:16:59,434 [main] DEBUG [org.springframework.core.env.StandardEnvironment] - Adding [systemProperties] PropertySource with lowest search precedence
2017-12-09 09:16:59,439 [main] DEBUG [org.springframework.core.env.StandardEnvironment] - Adding [systemEnvironment] PropertySource with lowest search precedence
2017-12-09 09:16:59,439 [main] DEBUG [org.springframework.core.env.StandardEnvironment] - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
2017-12-09 09:16:59,446 [main] INFO  [org.springframework.context.support.ClassPathXmlApplicationContext] - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@6c629d6e: startup date [Sat Dec 09 09:16:59 JST 2017]; root of context hierarchy
2017-12-09 09:16:59,504 [main] DEBUG [org.springframework.core.env.StandardEnvironment] - Adding [systemProperties] PropertySource with lowest search precedence
2017-12-09 09:16:59,505 [main] DEBUG [org.springframework.core.env.StandardEnvironment] - Adding [systemEnvironment] PropertySource with lowest search precedence
2017-12-09 09:16:59,505 [main] DEBUG [org.springframework.core.env.StandardEnvironment] - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
2017-12-09 09:16:59,516 [main] INFO  [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - Loading XML bean definitions from class path resource [spring-testLifeCycle.xml]
2017-12-09 09:16:59,532 [main] DEBUG [org.springframework.beans.factory.xml.DefaultDocumentLoader] - Using JAXP provider [com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl]
2017-12-09 09:16:59,587 [main] DEBUG [org.springframework.beans.factory.xml.PluggableSchemaResolver] - Loading schema mappings from [META-INF/spring.schemas]
2017-12-09 09:16:59,595 [main] DEBUG [org.springframework.beans.factory.xml.PluggableSchemaResolver] - Loaded schema mappings: {http://www.springframework.org/schema/tx/spring-tx-2.5.xsd=org/springframework/transaction/config/spring-tx-2.5.xsd, http://www.springframework.org/schema/context/spring-context-3.1.xsd=org/springframework/context/config/spring-context-3.1.xsd, http://www.springframework.org/schema/jms/spring-jms-2.5.xsd=org/springframework/jms/config/spring-jms-2.5.xsd, http://www.springframework.org/schema/util/spring-util-3.0.xsd=org/springframework/beans/factory/xml/spring-util-3.0.xsd, http://www.springframework.org/schema/tool/spring-tool.xsd=org/springframework/beans/factory/xml/spring-tool-4.0.xsd, http://www.springframework.org/schema/aop/spring-aop-3.2.xsd=org/springframework/aop/config/spring-aop-3.2.xsd, http://www.springframework.org/schema/context/spring-context-4.0.xsd=org/springframework/context/config/spring-context-4.0.xsd, http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd=org/springframework/web/servlet/config/spring-mvc-3.2.xsd, http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd=org/springframework/oxm/config/spring-oxm-3.0.xsd, http://www.springframework.org/schema/lang/spring-lang-3.2.xsd=org/springframework/scripting/config/spring-lang-3.2.xsd, http://www.springframework.org/schema/cache/spring-cache-3.2.xsd=org/springframework/cache/config/spring-cache-3.2.xsd, http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd=org/springframework/jdbc/config/spring-jdbc-3.1.xsd, http://www.springframework.org/schema/util/spring-util-2.0.xsd=org/springframework/beans/factory/xml/spring-util-2.0.xsd, http://www.springframework.org/schema/tool/spring-tool-3.2.xsd=org/springframework/beans/factory/xml/spring-tool-3.2.xsd, http://www.springframework.org/schema/context/spring-context.xsd=org/springframework/context/config/spring-context-4.0.xsd, http://www.springframework.org/schema/aop/spring-aop-4.0.xsd=org/springframework/aop/config/spring-aop-4.0.xsd, http://www.springframework.org/schema/jee/spring-jee-3.2.xsd=org/springframework/ejb/config/spring-jee-3.2.xsd, http://www.springframework.org/schema/context/spring-context-3.0.xsd=org/springframework/context/config/spring-context-3.0.xsd, http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd=org/springframework/jdbc/config/spring-jdbc-4.0.xsd, http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd=org/springframework/web/servlet/config/spring-mvc-4.0.xsd, http://www.springframework.org/schema/util/spring-util-2.5.xsd=org/springframework/beans/factory/xml/spring-util-2.5.xsd, http://www.springframework.org/schema/beans/spring-beans-3.2.xsd=org/springframework/beans/factory/xml/spring-beans-3.2.xsd, http://www.springframework.org/schema/aop/spring-aop-3.1.xsd=org/springframework/aop/config/spring-aop-3.1.xsd, http://www.springframework.org/schema/lang/spring-lang-4.0.xsd=org/springframework/scripting/config/spring-lang-4.0.xsd, http://www.springframework.org/schema/mvc/spring-mvc.xsd=org/springframework/web/servlet/config/spring-mvc-4.0.xsd, http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd=org/springframework/web/servlet/config/spring-mvc-3.1.xsd, http://www.springframework.org/schema/tool/spring-tool-4.0.xsd=org/springframework/beans/factory/xml/spring-tool-4.0.xsd, http://www.springframework.org/schema/tx/spring-tx-3.2.xsd=org/springframework/transaction/config/spring-tx-3.2.xsd, http://www.springframework.org/schema/lang/spring-lang-3.1.xsd=org/springframework/scripting/config/spring-lang-3.1.xsd, http://www.springframework.org/schema/cache/spring-cache-3.1.xsd=org/springframework/cache/config/spring-cache-3.1.xsd, http://www.springframework.org/schema/jee/spring-jee-4.0.xsd=org/springframework/ejb/config/spring-jee-4.0.xsd, http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd=org/springframework/jdbc/config/spring-jdbc-3.0.xsd, http://www.springframework.org/schema/jdbc/spring-jdbc.xsd=org/springframework/jdbc/config/spring-jdbc-4.0.xsd, http://www.springframework.org/schema/tool/spring-tool-3.1.xsd=org/springframework/beans/factory/xml/spring-tool-3.1.xsd, http://www.springframework.org/schema/cache/spring-cache-4.0.xsd=org/springframework/cache/config/spring-cache-4.0.xsd, http://www.springframework.org/schema/jee/spring-jee-3.1.xsd=org/springframework/ejb/config/spring-jee-3.1.xsd, http://www.springframework.org/schema/task/spring-task-3.2.xsd=org/springframework/scheduling/config/spring-task-3.2.xsd, http://www.springframework.org/schema/beans/spring-beans-3.1.xsd=org/springframework/beans/factory/xml/spring-beans-3.1.xsd, http://www.springframework.org/schema/util/spring-util.xsd=org/springframework/beans/factory/xml/spring-util-4.0.xsd, http://www.springframework.org/schema/aop/spring-aop-3.0.xsd=org/springframework/aop/config/spring-aop-3.0.xsd, http://www.springframework.org/schema/jms/spring-jms-3.2.xsd=org/springframework/jms/config/spring-jms-3.2.xsd, http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd=org/springframework/web/servlet/config/spring-mvc-3.0.xsd, http://www.springframework.org/schema/beans/spring-beans-4.0.xsd=org/springframework/beans/factory/xml/spring-beans-4.0.xsd, http://www.springframework.org/schema/beans/spring-beans.xsd=org/springframework/beans/factory/xml/spring-beans-4.0.xsd, http://www.springframework.org/schema/tx/spring-tx-3.1.xsd=org/springframework/transaction/config/spring-tx-3.1.xsd, http://www.springframework.org/schema/lang/spring-lang-3.0.xsd=org/springframework/scripting/config/spring-lang-3.0.xsd, http://www.springframework.org/schema/context/spring-context-2.5.xsd=org/springframework/context/config/spring-context-2.5.xsd, http://www.springframework.org/schema/task/spring-task-4.0.xsd=org/springframework/scheduling/config/spring-task-4.0.xsd, http://www.springframework.org/schema/tool/spring-tool-3.0.xsd=org/springframework/beans/factory/xml/spring-tool-3.0.xsd, http://www.springframework.org/schema/tx/spring-tx-4.0.xsd=org/springframework/transaction/config/spring-tx-4.0.xsd, http://www.springframework.org/schema/aop/spring-aop-2.0.xsd=org/springframework/aop/config/spring-aop-2.0.xsd, http://www.springframework.org/schema/jee/spring-jee-3.0.xsd=org/springframework/ejb/config/spring-jee-3.0.xsd, http://www.springframework.org/schema/task/spring-task-3.1.xsd=org/springframework/scheduling/config/spring-task-3.1.xsd, http://www.springframework.org/schema/beans/spring-beans-3.0.xsd=org/springframework/beans/factory/xml/spring-beans-3.0.xsd, http://www.springframework.org/schema/websocket/spring-websocket.xsd=org/springframework/web/socket/config/spring-websocket-4.0.xsd, http://www.springframework.org/schema/jee/spring-jee.xsd=org/springframework/ejb/config/spring-jee-4.0.xsd, http://www.springframework.org/schema/aop/spring-aop-2.5.xsd=org/springframework/aop/config/spring-aop-2.5.xsd, http://www.springframework.org/schema/jms/spring-jms.xsd=org/springframework/jms/config/spring-jms-4.0.xsd, http://www.springframework.org/schema/lang/spring-lang-2.0.xsd=org/springframework/scripting/config/spring-lang-2.0.xsd, http://www.springframework.org/schema/oxm/spring-oxm.xsd=org/springframework/oxm/config/spring-oxm-4.0.xsd, http://www.springframework.org/schema/jms/spring-jms-3.1.xsd=org/springframework/jms/config/spring-jms-3.1.xsd, http://www.springframework.org/schema/util/spring-util-3.2.xsd=org/springframework/beans/factory/xml/spring-util-3.2.xsd, http://www.springframework.org/schema/task/spring-task.xsd=org/springframework/scheduling/config/spring-task-4.0.xsd, http://www.springframework.org/schema/tool/spring-tool-2.0.xsd=org/springframework/beans/factory/xml/spring-tool-2.0.xsd, http://www.springframework.org/schema/tx/spring-tx-3.0.xsd=org/springframework/transaction/config/spring-tx-3.0.xsd, http://www.springframework.org/schema/lang/spring-lang-2.5.xsd=org/springframework/scripting/config/spring-lang-2.5.xsd, http://www.springframework.org/schema/jee/spring-jee-2.0.xsd=org/springframework/ejb/config/spring-jee-2.0.xsd, http://www.springframework.org/schema/jms/spring-jms-4.0.xsd=org/springframework/jms/config/spring-jms-4.0.xsd, http://www.springframework.org/schema/oxm/spring-oxm-3.2.xsd=org/springframework/oxm/config/spring-oxm-3.2.xsd, http://www.springframework.org/schema/tool/spring-tool-2.5.xsd=org/springframework/beans/factory/xml/spring-tool-2.5.xsd, http://www.springframework.org/schema/jee/spring-jee-2.5.xsd=org/springframework/ejb/config/spring-jee-2.5.xsd, http://www.springframework.org/schema/util/spring-util-4.0.xsd=org/springframework/beans/factory/xml/spring-util-4.0.xsd, http://www.springframework.org/schema/task/spring-task-3.0.xsd=org/springframework/scheduling/config/spring-task-3.0.xsd, http://www.springframework.org/schema/lang/spring-lang.xsd=org/springframework/scripting/config/spring-lang-4.0.xsd, http://www.springframework.org/schema/context/spring-context-3.2.xsd=org/springframework/context/config/spring-context-3.2.xsd, http://www.springframework.org/schema/jms/spring-jms-3.0.xsd=org/springframework/jms/config/spring-jms-3.0.xsd, http://www.springframework.org/schema/util/spring-util-3.1.xsd=org/springframework/beans/factory/xml/spring-util-3.1.xsd, http://www.springframework.org/schema/beans/spring-beans-2.0.xsd=org/springframework/beans/factory/xml/spring-beans-2.0.xsd, http://www.springframework.org/schema/oxm/spring-oxm-4.0.xsd=org/springframework/oxm/config/spring-oxm-4.0.xsd, http://www.springframework.org/schema/cache/spring-cache.xsd=org/springframework/cache/config/spring-cache-4.0.xsd, http://www.springframework.org/schema/tx/spring-tx.xsd=org/springframework/transaction/config/spring-tx-4.0.xsd, http://www.springframework.org/schema/beans/spring-beans-2.5.xsd=org/springframework/beans/factory/xml/spring-beans-2.5.xsd, http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd=org/springframework/oxm/config/spring-oxm-3.1.xsd, http://www.springframework.org/schema/tx/spring-tx-2.0.xsd=org/springframework/transaction/config/spring-tx-2.0.xsd, http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd=org/springframework/jdbc/config/spring-jdbc-3.2.xsd, http://www.springframework.org/schema/aop/spring-aop.xsd=org/springframework/aop/config/spring-aop-4.0.xsd, http://www.springframework.org/schema/websocket/spring-websocket-4.0.xsd=org/springframework/web/socket/config/spring-websocket-4.0.xsd}
2017-12-09 09:16:59,598 [main] DEBUG [org.springframework.beans.factory.xml.PluggableSchemaResolver] - Found XML schema [http://www.springframework.org/schema/beans/spring-beans.xsd] in classpath: org/springframework/beans/factory/xml/spring-beans-4.0.xsd
2017-12-09 09:16:59,676 [main] DEBUG [org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader] - Loading bean definitions
2017-12-09 09:16:59,693 [main] DEBUG [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - Loaded 1 bean definitions from location pattern [classpath:spring-testLifeCycle.xml]
2017-12-09 09:16:59,693 [main] DEBUG [org.springframework.context.support.ClassPathXmlApplicationContext] - Bean factory for org.springframework.context.support.ClassPathXmlApplicationContext@6c629d6e: org.springframework.beans.factory.support.DefaultListableBeanFactory@6adede5: defining beans [beanLifeCycle]; root of factory hierarchy
2017-12-09 09:16:59,708 [main] DEBUG [org.springframework.context.support.ClassPathXmlApplicationContext] - Unable to locate MessageSource with name 'messageSource': using default [org.springframework.context.support.DelegatingMessageSource@1f36e637]
2017-12-09 09:16:59,709 [main] DEBUG [org.springframework.context.support.ClassPathXmlApplicationContext] - Unable to locate ApplicationEventMulticaster with name 'applicationEventMulticaster': using default [org.springframework.context.event.SimpleApplicationEventMulticaster@3a883ce7]
2017-12-09 09:16:59,710 [main] DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@6adede5: defining beans [beanLifeCycle]; root of factory hierarchy
2017-12-09 09:16:59,711 [main] DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Creating shared instance of singleton bean 'beanLifeCycle'
2017-12-09 09:16:59,711 [main] DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Creating instance of bean 'beanLifeCycle'
2017-12-09 09:16:59,721 [main] DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Eagerly caching bean 'beanLifeCycle' to allow for resolving potential circular references
2017-12-09 09:16:59,722 [main] DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Invoking afterPropertiesSet() on bean with name 'beanLifeCycle'
Bean afterPropertiesSet.
2017-12-09 09:16:59,722 [main] DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Invoking init method  'start' on bean with name 'beanLifeCycle'
Bean start .
2017-12-09 09:16:59,724 [main] DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Finished creating instance of bean 'beanLifeCycle'
2017-12-09 09:16:59,725 [main] DEBUG [org.springframework.context.support.ClassPathXmlApplicationContext] - Unable to locate LifecycleProcessor with name 'lifecycleProcessor': using default [org.springframework.context.support.DefaultLifecycleProcessor@4d41cee]
2017-12-09 09:16:59,725 [main] DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Returning cached instance of singleton bean 'lifecycleProcessor'
2017-12-09 09:16:59,726 [main] DEBUG [org.springframework.core.env.PropertySourcesPropertyResolver] - Searching for key 'spring.liveBeansView.mbeanDomain' in [systemProperties]
2017-12-09 09:16:59,727 [main] DEBUG [org.springframework.core.env.PropertySourcesPropertyResolver] - Searching for key 'spring.liveBeansView.mbeanDomain' in [systemEnvironment]
2017-12-09 09:16:59,727 [main] DEBUG [org.springframework.core.env.PropertySourcesPropertyResolver] - Could not find key 'spring.liveBeansView.mbeanDomain' in any property source. Returning [null]
2017-12-09 09:16:59,727 [main] DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Returning cached instance of singleton bean 'lifecycleProcessor'
2017-12-09 09:16:59,728 [main] DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Returning cached instance of singleton bean 'beanLifeCycle'
2017-12-09 09:16:59,728 [main] INFO  [org.springframework.context.support.ClassPathXmlApplicationContext] - Closing org.springframework.context.support.ClassPathXmlApplicationContext@6c629d6e: startup date [Sat Dec 09 09:16:59 JST 2017]; root of context hierarchy
2017-12-09 09:16:59,728 [main] DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Returning cached instance of singleton bean 'lifecycleProcessor'
2017-12-09 09:16:59,728 [main] DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@6adede5: defining beans [beanLifeCycle]; root of factory hierarchy
2017-12-09 09:16:59,728 [main] DEBUG [org.springframework.beans.factory.support.DisposableBeanAdapter] - Invoking destroy() on bean with name 'beanLifeCycle'
Bean destroy.
2017-12-09 09:16:59,728 [main] DEBUG [org.springframework.beans.factory.support.DisposableBeanAdapter] - Invoking destroy method 'stop' on bean with name 'beanLifeCycle'
Bean stop.


---Spring Bean装配之Aware接口----------------------------------------------------
Aware接口:Spring中提供了一些以Aware结尾的接口,实现了Aware接口的bean在初始化之后,可以获取相应资源
·通过Aware接口,可以对Spring相应资源进行操作(一定要慎重,因为获取的资源可能是IOC容器的核心资源)
·为对Spring进行简单的扩展提供了方便的入口


例子
<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="moocApplicationContext" class="com.imooc.aware.MoocApplicationContext" ></bean> -->

 <bean id="moocBeanName" class="com.imooc.aware.MoocBeanName" ></bean>
       
 </beans>

public class MoocApplicationContext implements ApplicationContextAware  {
 
 @Override
 public void setApplicationContext(ApplicationContext applicationContext)
   throws BeansException {
  System.out.println("MoocApplicationContext : " + applicationContext.getBean("moocApplicationContext").hashCode());
 }
 
}
public class MoocBeanName implements BeanNameAware, ApplicationContextAware {

 private String beanName;
 
 @Override
 public void setBeanName(String name) {
  this.beanName = name;
  System.out.println("MoocBeanName : " + name);
 }

 @Override
 public void setApplicationContext(ApplicationContext applicationContext)
   throws BeansException {
  System.out.println("setApplicationContext : " + applicationContext.getBean(this.beanName).hashCode());
 }

}
@RunWith(BlockJUnit4ClassRunner.class)
public class TestAware extends UnitTestBase {
 
 public TestAware() {
  super("classpath:spring-aware.xml");
 }
 
// @Test
// public void testMoocApplicationContext() {
//  System.out.println("testMoocApplicationContext : " + super.getBean("moocApplicationContext").hashCode());
// }
 
 @Test
 public void textMoocBeanName() {
  System.out.println("textMoocBeanName : " + super.getBean("moocBeanName").hashCode());
 }
 
}

----Spring Bean装配之自动装配--------------------------

Bean的自动装配(Autowiring):减少配置文件中代码的行数
no           不自动装配,通过“ref”attribute手动设定。
byName       (与bean id 一致)根据属性名自动装配。根据Property的Name自动装配,如果一个bean的name,和另一个bean中的Property的name相同,则自动装配这个bean到Property中。
byType     (与bean id 没有关系,并不需要)根据Property的数据类型(Type)自动装配,如果一个bean的数据类型,兼容另一个bean中Property的数据类型,则自动装配。如果没有找到相匹配的bean,则什么事都不发生
byName与byType通过setter装配
constructor   根据构造函数参数的数据类型,进行byType模式的自动装配。如果没有找到与构造器参数相匹配的bean,则抛出异常
<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"
        default-autowire="byName">
       
        <bean id="autoWiringService" class="com.imooc.autowiring.AutoWiringService" ></bean>
       
        <bean id="autoWiringDAO" class="com.imooc.autowiring.AutoWiringDAO" ></bean>
 
 </beans>
public class AutoWiringDAO {
 
 public void say(String word) {
  System.out.println("AutoWiringDAO : " + word);
 }

}
public class AutoWiringService {
 
 private AutoWiringDAO autoWiringDAO;
 
 public AutoWiringService(AutoWiringDAO autoWiringDAO) {
  System.out.println("AutoWiringService");
  this.autoWiringDAO = autoWiringDAO;
 }

 public void setAutoWiringDAO(AutoWiringDAO autoWiringDAO) {
  System.out.println("setAutoWiringDAO");
  this.autoWiringDAO = autoWiringDAO;
 }
 
 public void say(String word) {
  this.autoWiringDAO.say(word);
 }

}
@RunWith(BlockJUnit4ClassRunner.class)
public class TestAutoWiring extends UnitTestBase {
 
 public TestAutoWiring() {
  super("classpath:spring-autowiring.xml");
 }
 
 @Test
 public void testSay() {
  AutoWiringService service = super.getBean("autoWiringService");
  service.say(" this is a test");
 }

}

===Spring Bean装配之Resources==================

通过Spring记载一些资源文件可以通过resource完成
这里写图片描述


ResourceLoader:对Resources进行加载的类。在Spring的IOC容器里,所有的application context都实现了ResourceLoader这个接口,也就是说所有的application context都可以用来获取resource的实例。
这里写图片描述
ResourceLoader注入参数时,前缀的类型:
这里写图片描述

    • classpath:从classpath中加载
    • file:从文件系统中作为url去加载
    • http:作为一个url加载
    • none:直接输入一个路径,依赖于application context

      针对于资源文件的统一接口
      <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="moocResource" class="com.imooc.resource.MoocResource" ></bean>
       
       </beans>
      public class MoocResource implements ApplicationContextAware  {
       
       private ApplicationContext applicationContext;
       
       @Override
       public void setApplicationContext(ApplicationContext applicationContext)
         throws BeansException {
        this.applicationContext = applicationContext;
       }
       
       public void resource() throws IOException {
        Resource resource = applicationContext.getResource("classpath:config.txt");//工程的classpath中配置了config.txt所在的path,所以可以找到。
        System.out.println(resource.getFilename());
        System.out.println(resource.contentLength());
       }

      }
      @RunWith(BlockJUnit4ClassRunner.class)
      public class TestResource extends UnitTestBase {
       
       public TestResource() {
        super("classpath:spring-resource.xml");
       }
       
       @Test
       public void testResource() {
        MoocResource resource = super.getBean("moocResource");
        try {
         resource.resource();
        } catch (IOException e) {
         e.printStackTrace();
        }
       }
       
      }

原文地址:https://www.cnblogs.com/charles999/p/6590103.html