Spring到springBoot入门学习篇(二.1)

二、SpringIOC(配置)

2.1接口及面向接口编程

  1. 用于沟通的中介物的抽象化
  2. 实体把自己提供给外界的一种抽象化说明,用以由内部操作分离出外部沟通方法,使其能被修改内部而不影响外界其他实体与其交互的方式
  3. 对应Java接口即声明,声明了哪些方法是对外公开提供的在Java8中,接口可以拥有方法体
  4. 结构设计中,分清层次及调用关系,每层只向外(上层)提供一组功能接口,各层间仅依赖接口而非实现类接口实现的变动不影响各层间的调用,这一点在公共服务中尤为重要
  5. “面向接口编程”中的“接口”是用于隐藏具体实现和实现多态性的组件

面向接口的编程:

定义一个接口类

写一个实现的接口类

Main()

{

      接口类 test=new 实现类()

      test.()调用方法,实现为用户提供功能,而不公开实现的代码

}

2.2什么是IOC控制反转

1.IOC:控制反转

控制权的转移,应用程序本身不负责依赖对象的创建和维护,而是由外部容器负责创建和维护。

当我们需要对象时,并非像传统的方式去new一个对象,而是向外部容器去申请这个对象。例如我们的住房不需要自己亲手建(耗时、耗力)通过开发商去购买来用就行。对于我们的应用容器,关注的是对象的使用,而不是关注对象的创建

2.DI依赖注入

依赖注入是其一种实现方式,所谓依赖注入,就是由IOC容器在运行期间,动态地将某种依赖关系注入到对象之中。

图解如下:

当你需要一个类时,并不像传统的new一个对象的方式,而是通过IOC容器中去获取这个类的对象,从而使用这个对象。

通过xml文件注入依赖的写法:

<bean id="onelnterface(我们定义的名称)"class="com.imooc.ioc.interfaces.Onelnterfacelmp/(这是实体实现类的位置:包名.类名)"></bean>

 

2.3Bean容器初始化

  1. 基础:两个包

org.springframework.beans

org.springframework.context

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

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

 

  1. -本地文件

Classpath:相对路径,相对工程目录

Web应用中依赖servlet或Listener

目的:创建对象并且组装对象之间的关系

 

2.5Spring 注入

Spring注入是指在启动Spring容器加载bean配置的时候,完成对bean中的成员变量的赋值行为,常用的两种注入方式

1.设值注入:成员变量的Set方法进行注入

指:有一个setInjectionDAO()的方法,而对这个方法的赋值参数是injectionDAO

2.构造注入:

指:在bean创建injectionServic对象时候,初始化构建函数时,在构造函数中成员变量的赋值。

实例:

1.spring-injection.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="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>

2.java代码片段如下:

(1)面向接口:

模拟数据库数据获取,及数据操作

package com.imooc.ioc.injection.dao;

public interface InjectionDAO {
	
	public void save(String arg);
	
}
package com.imooc.ioc.injection.dao;

import org.springframework.stereotype.Repository;

//数据库操作的实现类
@Repository
public class InjectionDAOImpl implements InjectionDAO {
	
	public void save(String arg) {
		//模拟数据库保存操作
		System.out.println("保存数据:" + arg);
	}

}

 模拟数据处理:

package com.imooc.ioc.injection.service;

public interface InjectionService {
	
	public void save(String arg);
	
}
package com.imooc.ioc.injection.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.imooc.ioc.injection.dao.InjectionDAO;


//用于数据处理于调用数据库操作
@Service
public class InjectionServiceImpl implements InjectionService {
	
	//第一种方式:自动配置成员变量,自动从xml文件中获得id=injectionDAO的对象
	@Autowired
	private InjectionDAO injectionDAO;
	
	//第二种方式:构造器注入
	public InjectionServiceImpl(InjectionDAO injectionDAO1) {
		this.injectionDAO = injectionDAO1;
	}
	
	//第三种方式:设值注入
	public void setInjectionDAO(InjectionDAO injectionDAO) {
		this.injectionDAO = injectionDAO;
	}

        //被Test类调用的函数,在调用前已经通过上面的三种初始化的其一方式进行初始化变量injectionDAO
	public void save(String arg) {
		//模拟业务操作
		System.out.println("Service接收参数:" + arg);
		arg = arg + ":" + this.hashCode();
                //调用该变量injectionDAO的方法
		injectionDAO.save(arg);
	}
	
}
//用于数据处理数据操作
@Service
public class InjectionServiceImpl implements InjectionService {
	
	//自动配置成员变量
	@Autowired
	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);
	}
	
}

(2)Test测试类,加载容器,并调用@Service类方法执行:

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() {
                //调用Service逻辑处理类,通过ioc容器获得对象
		InjectionService service = super.getBean("injectionService");
		service.save("这是要保存的数据");
	}
	
	
	
}

 

2.6Spring的Bean配置:

1.Bean配置项

Id:bean的唯一标识

Class:具体需要实例化的哪个类

Scope:范围,作用域

Constructor arguments:构造器注入的参数

Properties:属性,set值注入的参数

Autowiring mode:自动装配模式

lazy-initialization mode:懒加载模式

Initialization/destruction method:初始化、销毁的方法

 

2.Bean的作用域scope

(1)singleton:单例,指一个Bean容器中只存在一份(默认),即获得的对象实例是相同的

<bean id="mybeanScope" class="com.imooc.bean.BeanScope" scope="singleton"></bean>

 

(2)prototype:每次请求(每次使用)创建新的实例,即在同一个容器中获得的对象仍是不同的

      //通过对象的hashcode即可判断是否是统一对象
      @Test
      public void testSay() {

             //获得加载容器的bean,因为对该bean配置了prototype范围,则对应获取到的bean对象不是同一个对象
             BeanScope mybeanscope=super.getBean("mybeanScope");

             mybeanscope.say();//hashcode: 25548982

             BeanScope mybeanscope2=super.getBean("mybeanScope");

             mybeanscope2.say();//hashcode: 1468303011

      }

 

(3)request:每次http请求创建一个实例且仅在当前request内有效

(3)session:同上,每次http请求创建,当前session内有效

(4)global session:基于portlet的web中有效(portlet定义了global session),如果是在web中,同session

 

2.7Bean的生命周期

1.定义在xml中定义的bean

2.初始化通过new一个xml容器对象,在容器对象.getBean()初始化一个对象,如何对于该对象的变量进行初始化:

(bean对象初始化方法1)实现org.springframework.beans.factory.InitializingBean接口覆盖afterPropertiesSet方法

public class ExampleInitializingBean implements InitializingBean{

@Override

public void afterPropertiesSet0 throws Exception{

//做一些类的初始化工作

}

(bean对象初始化方法1)配置init-method

<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/>

public class ExampleBean{

public void init(){

//do some initialiaation work

}}

3.使用

处理实际的业务逻辑问题

4.销毁

bean容器停止时,由bean容器去销毁bean的实例

(bean对象销毁方法1)实现org.springframework.beans.factory.DisposableBean接口覆盖destroy方法

public class ExampleDisposableBean implements DisposableBean{

@Override

public void destroy0 throws Exception{

//do something

}

(bean对象销毁方法2)配置destroy-method

<bean id="exampleInitBean"class="examples.ExampleBean" destroy-method="cleanup"/>

public class ExampleBean{.

public void cleanup(){

//do some destruction work(like releasing pooled connections)

}

 

5.配置全局默认初始化:init()、销毁方法:destroys()
 

<?xml version="1.0"encoding="UTF-8?>

 <beans xmlns="http:/www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001XMLSchema-instance"

xsi:schemaLocation="http:/www.springframework.org/schema/beans http:/www.springframeworkorg/schema/beans/spring-beans.xsd"

default-init-method="init" default-destroy-method="destroys>

</beans>

 

7.实例:

public class BeanLifeCycle implements 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最先被调用(初始化则最先执行该函数)
@Override
public void afterPropertiesSet() throws Exception {

     System.out.println("Bean afterPropertiesSet.");

}

//在override函数初始化后,仍能执行自定义的全局初始化方法
public void start() {

     System.out.println("Bean start .");

}

//在override函数销毁后,仍能执行自定义的全局销毁方法
public void stop() {

     System.out.println("Bean stop.");

}


}

 

2.8Bean的自动装配

1.No:不做任何操作(默认)

2.byname:根据属性名自动装配。此选项将检查容器并根据名字查找与属性完全一致的bean,并将其与属性自动装配

3.byType:如果容器中存在一个与指定属性类型相同的bean,那么将与该属性自动装配;如果存在多个该类型bean,那么抛出异常,并指出不能使用byType方式进行自动装配;如果没有找到相匹配的bean,则什么事都不发生

4.Constructor:与byType方式类似,不同之处在于它应用于构造器参数。如果容器中没有找到与构造器参数类型一致的bean,那么抛出异常

 

byname类型的实例:

设置自动配置的类型为byName后,对类变量的初始化就不需要写设值注入了,它可以自动匹配set方法,

public class AutoWiringService {

private AutoWiringDAO autoWiringDAO;

//初始化的时候会自动装配,不需在xml配置问价中写设值的<property name="" ref="">操作
//但是setXXXX 中的XXXX必须和<bean 的id="XXXX"同名> 
public void setAutoWiringDAO(AutoWiringDAO autoWiringDAO) {
     System.out.println("setAutoWiringDAO");
     this.autoWiringDAO = autoWiringDAO;

}
public void say(String word) {
     this.autoWiringDAO.say(word);

}

}

byType的类型: 即使bean id的定义与对应的setXXX(XX xx)里面的名称不同,也可以被自动配置,因为它是作为类型而自动配置的

 

Construction类型:

public class AutoWiringService {

private AutoWiringDAO autoWiringDAO;

//通过构造器对对象变量进行配置

public AutoWiringService(AutoWiringDAO autoWiringDAO) {

    System.out.println("AutoWiringService");

    this.autoWiringDAO = autoWiringDAO;

}

public void say(String word) {

    this.autoWiringDAO.say(word);

}

}

2.9Resources&ResourceLoader

1.针对于资源文件的统一接口

Resources

UrlResource:URL对应的资源  ,根据一个URL地址即可构建

ClassPathResource:获取类路径下的资源文件

FileSystemResource:获取文件系统里面的资源

ServletContextResource:ServletContext封装的资源,用于访问ServletContext环境下的资源

InputStreamResource:针对于输入流封装的资源

ByteArrayResource:针对于字节数组封装的资源

 

2.ResourceLoader

All application contexts implement the ResourceLoader interface, and therefore all application contexts may be used to obtain Resource instances.

public interface ResourceLoader {

Resource getResource(String location)

}

Resource template=ctx. getResource("some/resource/path/myTemplate. txt");

Resource template=ctx. getResource("classpath: some/resource/path/myTemplate. txt")

Resource template =ctx.getResource("file:/some/resource/path/myTemplate. txt");

Resource template =ctx.getResource("http:http://xx/xxx/x ");

 

例子:

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="moocResource" class="com.imooc.resource.MoocResource" ></bean>
	
 </beans>

 java代码:

public class MoocResource implements ApplicationContextAware  {

  private ApplicationContext applicationContext;

  @Override//设置初始化

  public void setApplicationContext(ApplicationContext applicationContext)

         throws BeansException {
     this.applicationContext = applicationContext;
  }

  public void resource() throws IOException {
     // applicationContext作为  ResourceLoader使用,文件在
     //上下;两种路径都行,在该main
     //Resource resource = applicationContext.getResource("config.txt");  //没有加前缀时候,它的路径依赖于ApplicationContext,而ApplicationContext对象的获取是单元测试类中有定义的
calsspath-->默认依赖于calsspath方式加载
     //Resource resource = applicationContext.getResource("classpath:config.txt");
     //Resource resource = applicationContext.getResource("file:C:\\Users\\401\\eclipse-workspace\\Spring\\src\\main\\resources\\config.txt");
     Resource resource = applicationContext.getResource("url:http://www.baidu.com/");
     System.out.println(resource.getFilename());
     System.out.println(resource.contentLength());

  }

}

 

因为main/resourcesclasspath的路径中,所以系统可以根据查找所有的path路径而找到config.txt文件

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值