Spring课程 Spring入门篇 2-1 IOC和bean容器

课程链接:

本节讲了5部分内容,6为项目demo:

1  接口及面向接口编程

2  什么是IOC

3  Spring的bean配置

4  Bean的初始化

5  Demo

自己理解:

1  高层模块和底层模块都依赖于他们共同的接口,而不是高层模块依赖于底层模块进行开发

2  IOC 控制反转,控制权的转移,将产生对象的过程反转了过来。本来由高层模块new对象,现在将创建对象的任务交给了外部容器。实现方式是依赖注入DI

3  参见demo2,spring-ioc.xml中bean的配置

    对spring bean的使用(注入)有两种方式,一种是xml配置,一种是注解的方式,本节主要采用xml的方式

4  基础两个包:org.springframework.beans   和  org.springframework.context  

    方式:ApplicationContext,参见基类

  

1 加载文件
FileSystemXmlApplicationContext context1 = new FileSystemXmlApplicationContext("F:/xiangmu3/Xin/FuQiang/Spring/ddwei-dao/target/classes/spring-ioc.xm");
2 加载路径
ClassPathXmlApplicationContext context new ClassPathXmlApplicationContext(springXmlPath.split("[,\s]+"));
3  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>

1  接口及面向接口编程

1.1  java8拥有方法体

1.2  接口只声明不实现

1.3  接口只能有声明,抽象类既可以有声明,也可以有实现;类中只能实现

6  Demo

共两个案例,

Demo1:

1  介绍面向接口编程的Demo

Demo2:

1  控制反转应用演示 (产生对象的过程由容器负责,不再由类去创建) 

注意事项:spring-*.xml必须放在项目的classpath下(右击项目==》project==》buildpath==》source==》最下边是项目的默认classpath路径),否则不加载

 Demo1:

测试类:

package com.imooc.bean.ioc.interfaces;

public class Main {
    
    
    /**
     * 面向接口编程的简单说明,用接口声明,
     * 将接口的实现类赋值给对象的声明,然后进行调用
     * @param args
     */
    public static void main(String[] args) {
        OneInterface oif = new OneInterfaceImpl();
        System.out.println(oif.hello("word."));;
    }

}

接口:

package com.imooc.bean.ioc.interfaces;

public interface OneInterface {
    
    String hello(String word);

}

实现类:

package com.imooc.bean.ioc.interfaces;


public class OneInterfaceImpl implements OneInterface{

    @Override
    public String hello(String word) {
        // TODO Auto-generated method stub
        return "Word form interfacce"OneInterface":"+word;
    }

}

 Demo2:

测试类:

package com.imooc.test.ioc.interfaces;

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

import com.imooc.bean.ioc.interfaces.OneInterface;
import com.imooc.bean.ioc.interfaces.OneInterfaceImpl;
import com.imooc.test.base.UnitTestBase;
/**
 * The Question We Need To Focus:
 * 1    ioc-spring.xml的路径必须放在classpath下边,否则无法加载xml
 * @author weijingli
 *
 */
@RunWith(BlockJUnit4ClassRunner.class)
public class TestOneInterface extends UnitTestBase {
    
    public TestOneInterface(){
        super("classpath*:spring-ioc.xml");
    }
    
    
    @Test
    public void testHello() {
        // TODO Auto-generated method stub
        OneInterface oif = super.getbean("oneInterface");
        System.out.println(oif.hello("myInput"));
    }

}

接口:

package com.imooc.bean.ioc.interfaces;

public interface OneInterface {
    
    String hello(String word);

}

实现类:

package com.imooc.bean.ioc.interfaces;


public class OneInterfaceImpl implements OneInterface{

    @Override
    public String hello(String word) {
        // TODO Auto-generated method stub
        return "Word form interfacce"OneInterface":"+word;
    }

}

基类:

package com.imooc.test.base;

import org.apache.commons.lang.StringUtils;
import org.junit.After;
import org.junit.Before;
import org.springframework.beans.BeansException;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/*

1 加载文件
FileSystemXmlApplicationContext context1 = new FileSystemXmlApplicationContext("F:/xiangmu3/Xin/FuQiang/Spring/ddwei-dao/target/classes/spring-ioc.xm");
2 加载路径
ClassPathXmlApplicationContext context new ClassPathXmlApplicationContext(springXmlPath.split("[,\s]+"));

*/

public class UnitTestBase {
    
    //spring-core的jar包下
    private ClassPathXmlApplicationContext context;
    
    private String springXmlPath;
    
    public UnitTestBase(){
        
    }
    
    //初始化该类,刚进来时传入xml路径
    public UnitTestBase(String springXmlPath){
        this.springXmlPath = springXmlPath;
    }
    
    //StringUtils在common-lang-2.4包下
    @Before
    public void before(){
        if(StringUtils.isEmpty(springXmlPath)){
            springXmlPath="classpath*:spring-*.xml";
        }
        try{
            context = new ClassPathXmlApplicationContext(springXmlPath.split("[,\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) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
        
    }
    
    protected <T extends Object> T getbean(Class <T> clazz){
        return context.getBean(clazz);
    }

}

spring-ioc.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"
default-init-method="init" default-destroy-method="destroy">

<bean id="oneInterface" class="com.imooc.bean.ioc.interfaces.OneInterfaceImpl"></bean> 


</beans>

pom.xml(maven通用)

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

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.ddwei</groupId>
  <artifactId>ddwei-dao</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <name>ddwei-dao</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.10</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>
原文地址:https://www.cnblogs.com/1446358788-qq/p/10116485.html