springNote - juedaiyuer/researchNote GitHub Wiki

#Spring笔记[一]#

##IOC##

控制反转,应用程序本身不负责依赖对象的创建和维护,而是由外部容器负责创建和维护
DI(依赖注入)是一种实现方式

##步骤##

  1. 找IOC容器
  2. 容器返回对象
  3. 使用对象

##实现IoC通常有三种方式##

  1. 利用接口或者继承,一般以接口较多.这种实现方式和lazy load相同
  2. 构造函数注入
  3. 属性注入

##spring容器##

spring Ioc container

###bean定义###

配置元数据(metadata)

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"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
                http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

    <bean id="..." class = "...">
		<!-- collaborators and configuration for this bean go here -->	
	</bean>

	<bean id="..." class="...">
	    <!-- collaborators and configuration for this bean go here -->
	</bean>
		<!-- more bean definitions go here -->	
</beans>

Bean的配置项

  1. bean id="类名" class="位置(包名.类名)"
  2. id:标识该bean的名称,通过factory.getBean("id")来获得实例
  3. name:给bean起个别名
  4. Singleton:默认为true,单实例模式.如果是false,即原型模式,每一次获取都是一个新的实例
  5. Init-method:在bean实例化后要调用的方法(已定义好)
  6. Destroy-method:bean从容器里删除之前要调用的方法

实例化容器

应用上下文接口org.springframework.context.ApplicationContext代表了spring Ioc容器;负责实例化,配置和组装beans

ApplicationContext context = new ClassPathXmlApplicationContext(new string[]{"services.xml","daos.xml"})

context.getBean("id"); //方法来获取bean的实例

##一个spring例子##

定义一个接口

package juedaiyuer;

public interface OneInterface 
{
	public void  say(String arg);
}

接口的一个实现类

package juedaiyuer;

public class OneInterfaceImpl implements OneInterface {

	@Override
	public void say(String arg) {
		System.out.println("悄悄话:"+arg);

	}
}

spring的配置

spring-ioc.xml(文件在src目录下)

<?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="oneInterface" class="juedaiyuer.OneInterfaceImpl"></bean>

</beans>

单元测试父类

package 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;

import juedaiyuer.OneInterface;

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.split("[,\\s]+"));
			context.start();
			System.out.println("单元测试基类---Before");
		} catch (BeansException e) {
			e.printStackTrace();
		}

	}

	@After
	public void after() {
		context.destroy();
		System.out.println("单元测试基类---After");
	}

	@SuppressWarnings("unchecked")
	protected <T extends Object> T getBean(String beanId) {
		try {
			System.out.println("单元测试基类---通过id获取实例");
			return (T) context.getBean(beanId);

		} catch (BeansException e) {
			e.printStackTrace();
			return null;
		}
	}

	protected <T extends Object> T getBean(Class<T> clazz) {
		try {
			System.out.println("单元测试基类---通过clazz获取实例");
			return (T) context.getBean(clazz);
		} catch (BeansException e) {
			e.printStackTrace();
			return null;
		}
	}

}

单元测试

package test.base;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;

import juedaiyuer.OneInterface;

@RunWith(BlockJUnit4ClassRunner.class)
public class TestOneInterfaceImpl  extends UnitTestBase{
	public TestOneInterfaceImpl()
	{
		super("classpath*:spring-ioc.xml");
	}

	@Test
	public void testSay()
	{
		OneInterface oneInterface = super.getBean("oneInterface");
		oneInterface.say("this is a test");
	}

}

示例代码

示例代码


##spring的实例化##

###构造器实例化###

<bean id="oneInterface" class="juedaiyuer.OneInterfaceImpl"></bean>

//测试代码

package juedaiyuer;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class test {

	public static void main(String[] args) {
		ApplicationContext  ctx = new ClassPathXmlApplicationContext(new String[]{"spring-ioc.xml"});
		OneInterface  oneinterface =   (OneInterface) ctx.getBean("oneInterface");
	
		oneinterface.say("提莫队长正在待命");
	}

}

##spring注入##

  1. 设值注入
  2. 构造注入

###代码示例###

public interface InjectionDAO {

	public void save(String arg);

}

public class InjectionDAOImpl implements InjectionDAO {

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

}

public interface InjectionService {

	public void save(String arg);

}

public class InjectionServiceImpl implements InjectionService {

	private InjectionDAO injectionDAO;

	//构造器注入
	public InjectionServiceImpl(InjectionDAO injectionDAO1) {
		this.injectionDAO = injectionDAO1;
	}

	//设值注入
	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配置

<?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="injectionService" class="com.imooc.ioc.injection.service.InjectionServiceImpl"> -->
<!--         	<property name="injectionDAO" ref="injectionDAO"></property> -->
<!--         </bean> -->

		<bean id="injectionService" class="com.imooc.ioc.injection.service.InjectionServiceImpl">
	    	<constructor-arg name="injectionDAO" ref="injectionDAO"></constructor-arg>
	    </bean>
	    
	    <bean id="injectionDAO" class="com.imooc.ioc.injection.dao.InjectionDAOImpl"></bean>

</beans>

单元测试

package com.imooc.test.ioc.interfaces;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;

import com.imooc.ioc.injection.service.InjectionService;
import com.imooc.test.base.UnitTestBase;

@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("这是要保存的数据");
	}

}	

##Eclipse中spring的配置##

project-properties:

Java Build Path选项中加入相依赖的jar文件


##spring quick start##

官网描述方法的一个尝试

<dependencies>
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-context</artifactId>
	    <version>4.2.5.RELEASE</version>
	</dependency>
</dependencies>

#source#

  1. imooc
  2. spring2.0技术手册(百度云---码农/java)
  3. springFramework4.x参考文档ZH
  4. Spring IOC容器中实例化bean(evernote)
  5. Java笔记 – 泛型

#Bug思考#

不要忘记commons-logging的jar引入,不然会报错

//错误代码
java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
⚠️ **GitHub.com Fallback** ⚠️