Spring5--IOC

 

简介

   spring已经成为了java开发人员必备的框架,spring基本引领着整个java开发方向的流程,现在spring提供了五花八门的模块来帮助开发人员进行各种java项目的构建,在spring5中提出了非阻塞的web框架。

Spring的安装

   Spring的安装非常的简单,只要使用在maven中引入相应的java即可完成安装

<dependencies>
       <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-context</artifactId>
           <version>5.0.8.RELEASE</version>
       </dependency>
       <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-core</artifactId>
           <version>5.0.8.RELEASE</version>
       </dependency>

   </dependencies>

下面我们创建一个Spring的java文件,在Spring4之后,就可以使用基于Annotation的方式来完全替换原有的xml的方法,但是我们这部分的内容会两个方式都简单进行介绍。我们首先通过基于Annotation的方式来创建一个Spring的项目,以此验证spring是否安装成功。

@Configuration
public class HelloSpringConfig {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(HelloSpringConfig.class);
        String hello = applicationContext.getBean("hello", String.class);
        System.out.println(hello);
    }
    @Bean("hello")
    public String getHello(){
     return "hello world Spring5";
    }
}

@Configuration声明的类就表示该类是一个配置类,就等于原来的beans.xml文件,类中的方法getHello上使用@Bean,这说明该方法会返回一个String类型的对象。在main方法中通过AnnotationConfigApplicationContext 将该配置文件加载进去到spring的上下文中,spring的上下文就等于一个大容器,spring通过这个容器来管理所有的对象,通过getBean方法可以获取刚才创建的bean,然后输出结果。

以上程序将会输入hello这个字符串,只要能运行成功说明spring 的环境已经正确的安装完成,下面我们将介绍spring 的IOC的作用和意义。

IOC介绍

OC是控制反转,它是spring非常重要的一个特性,它是spring学习的基础,Ioc也成为DI(依赖注入),简单来说就是把spring变成一个容器,由spring来控制对象的创建和他们之间的依赖关系,下面我们通过一个实例来给大家讲解spring的IOC的使用和意义。

用简单的java代码演示,为什么使用IOC?

  java代码十分简单

   Knight:

public class Knight {
    private String username;
    private Weapon weapon;

    public Knight(String username,Weapon weapon) {
        this.username = username;
        this.weapon = weapon;
    }
    //省略了getter和setter
    public void fight() {
        weapon.attack();
    }

  和Weapon相关的代码

public interface Weapon {
    void attack(String name);
}

public class Axe implements Weapon {
    public void attack(String name) {
        System.out.println(name+"提起斧头,向人砍去");
    }
}

public class Gun implements Weapon {
    public void attack(String name) {
        System.out.println(name+"用枪打你啊");
    }
}

public class Knife implements Weapon{
    public void attack(String name) {
        System.out.println(name+"提着大刀,看人去");
    }
}

下面就是Knight中如何创建Weapon的问题,最原始的方案就是在使用new来创建具体的Weapon实例

public class Test {
   public static void main(String[] args){
       Weapon w = new Axe();
       Knight tom = new Knight("tom", w);
       tom.fight();
   }
}

这种方案最大的问题就是依赖于一个具体的实现类,将来如果要修改Weapon的实现类所有的代码都需要调整,丧失了灵活性,第二种方案是基于工厂的模式来创建,这里使用简单工厂来演示。

public class SimpleFactory {
    public static Weapon getWeapon() {
        return new Knife();
    }
}


public class Test {
   public static void main(String[] args){
      /* Weapon w = new Axe();
       Knight tom = new Knight("tom", w);
       tom.fight();*/
       Weapon weapon = SimpleFactory.getWeapon();
       Knight tom = new Knight("tom", weapon);
       tom.fight();
   }
}

这种方案将来如果希望修改Weapon的实现类只要修改一个地方即可,这种方法虽然解决了灵活性的问题,但将来修改的时候需要调整源代码,所以这种方式也不是很理想,最佳的方案是将具体的类写到一个配置文件中,通过读取配置文件来创建具体的对象。创建一个factory.properties文件来存储具体的对象

weapon = com.el.spring5.Gun

为了方便确定那些对象需要创建,可以自己定义一个Annotation来指定要创建的对象

@Retention(RUNTIME)
public @interface Inject {
    public String value() default "";
}

然后在需要创建的对象的setter方法上添加该Annotation

@Inject
public void setWeapon(Gun weapon) {
  this.weapon = weapon;
}

让所有需要添加这个对象的类继承于一个基类,在这个基类中来创建所有的对象

ublic class Base {
    public Base() {
        try {
            Properties prop = new Properties();
            prop.load(Base.class.getClassLoader()
                    .getResourceAsStream("factory.properties"));
            //通过反射来读取需要创建对象的信息
            Method[]ms =  this.getClass().getDeclaredMethods();
            for(Method m:ms) {
                if(m.isAnnotationPresent(Inject.class)) {
                    Inject in = m.getAnnotation(Inject.class);
                    String name = null;
                    //获取对象key
                    if("".equals(in.value())) {
                        //没有指定,就默认通过setXXX方法来处理,把set去掉,然后第一个字母小写
                        name = m.getName();
                        name = name.substring(3);
                        name = name.substring(0, 1).toLowerCase()+name.substring(1);
                    } else {
                        name = in.value();
                    }
                    String o = prop.getProperty(name);
                    if(o!=null) {
                        //创建对象
                        Object obj = Class.forName(o).newInstance();
                        //调用方法创建对象
                        m.invoke(this, obj);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Base是所有需要创建对象的基类,此处Knight需要继承于Base这个基类,只要创建Knight,就会自动调用父类不带参数的构造方法来完成对象的注入。这就是依赖注入的一种通过这种方式,只要继承于Base这个类的所有类,都支持这种依赖注入的方式,这就是spring的DI所做的事情,spring提供了一个大容器来管理所有的对象依赖,接下来我们首先通过spring的xml配置文件来完成同样的操作。

基于xml的配置方式

首先在资源文件中创建beans.xml,并且引入spring的schema

<?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">
</beans>

在该文件中可以直接创建具体的对象和依赖关系

<?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="weapon" class="com.el.spring5.Knife"/>
    <bean id="knight" class="com.el.spring5.Knight">
        <property name="weapon" ref="weapon"/>
    </bean>

</beans>

创建了两个bean,一个是weapon,weapon的类型是Knife,另外一个是knight,其中knight依赖于weapon,接着只要通过spring的ApplicationContext来创建对象就会被spring所管理。

 public static void main(String[] args) {
       ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
       Knight k = (Knight)ctx.getBean("knight");//根据beans.xml中的id来获取对象
       k.fight();
   }

在spring3之后就提供了基于Annotation的方式来进行对象的管理,这样可以简单大量的配置操作。

基于Annotation的方式

  首先在beans.xml中开启Annotation的支持,并且设定需要扫描的包,需要加入context的schema

<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <context:annotation-config/>
    <context:component-scan base-package="com.el.spring5.annotation.*"/>
</beans>

之后在需要spring管理对象中添加@Component的Annotation,在需要注入的对象的setter方法上添加@Autowired,首先看看几种武器的设置

@Component("axe")
public class Axe implements Weapon {
    ...
}
@Component("gun")
public class Gun implements Weapon {
    ...
}
@Component("knife")
public class Knife implements Weapon {
    ...
}

这里创建了三个对象axe,gun和knife,但是此时Knight的setWeapon使用了@Autowired进行注入,由于方法是setWeapon,所以会找weapon的对象,显然没有,此时需要指定要注入的对象类型,使用@Qualifier来进行设定

@Component("knight")
public class Knight {
    private String username;
    private Weapon weapon;
    ...
    @Autowired
    @Qualifier("axe")
    public void setWeapon(Weapon weapon) {
        this.weapon = weapon;
    }
}

main函数的代码不用进行任何修改,可以直接运行。在spring4之后提供了基于java的配置方式,此时连xml 文件都不需要,下面就来看看这种方式

基于java配置文件的方式

 在spring的新版本中,提供纯java的支持方式,此时甚至都不需要添加如何的xml文件,但需要专门创建一个java的配置类,在该类上增加一些配置说明。

@Configuration
@ComponentScan("com.el.spring5")
public class BaseConfiguration {
}

其他的类的设定不变,最后在调用的时候有一些基本的区别。

public class Test {
    public static void main(String[] args) {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(BaseConfiguration.class);
        Knight k = (Knight)ctx.getBean("knight");
        k.fight();
        ((AnnotationConfigApplicationContext)ctx).close();
    }
}

以上内容就是spring的IOC的主要内容,IOC是spring的最基础,它让所有的类被spring所管控,这样spring就可以非常方便的为开发人员提供各种功能。

猜你喜欢

转载自blog.csdn.net/qq_39736103/article/details/82380270
今日推荐