Spring_HelloWord

环境:IntelliJ 14 ; jdk1.8

Spring操作步骤

1.新建项目---Spring Batch

2.IntelliJ会自动加载jar包

3.现在就可以在src目录下写Java类文件了

4.将相应的类部署在XML配置文件spring-config.xml中 (Eclipse需要手动创建,貌似名为bean.xml)

5.写主程序main (右键-->Run)

HelloWord小程序

此处直接从第3步开始

3.首先定义两个接口,Person和Axe

public interface Person {
    public void useAxe();
}
public interface Axe {
    public String chop();
}

然后定义接口的实现类,Chinese和StoneAxe

public class Chinese implements Person {
    private Axe axe;
    //设值注入
    public void setAxe(Axe axe) {
        this.axe = axe;
    }

    @Override
    public void useAxe() {
        System.out.println(axe.chop());

    }
}
public class StoneAxe implements Axe {
    @Override
    public String chop() {
        return "石斧砍柴好慢";
    }
}

4.修改spring-config.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="chinese" class="org.spring.service.impl.Chinese">
              <property name="axe" ref="stoneAxe"/>
       </bean>
       <bean id="stoneAxe" class="org.spring.service.impl.StoneAxe"/>
</beans>

5.写主程序main

public class SpringTest {
    public static void main(String[] args){
        ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml");
        Person p = (Person) ctx.getBean("chinese", Person.class);
        p.useAxe();
    }
}

程序到此结束,运行结果为:

石斧砍柴好慢

Spring的核心机制:依赖注入(Dependency Inhection)(控制反转IoC—Inversion of Control)

依赖注入通常包括以下两种:

设值注入:使用属性的setter方法来注入被依赖的实例

构造注入:使用构造器来注入被依赖的实例

请看下面的例子

public class Chinese implements Person {
    private Axe axe;

   //设值注入
    public void setAxe(Axe axe) {
        this.axe = axe;
    }

    //构造注入
    public Chinese(Axe axe) {
        this.axe = axe;
    }

    @Override
    public void useAxe() {
        System.out.println(axe.chop());

    }
}

不同的注入方式在配置文件中的配置也不一样

<!--设值注入-->
<bean id="chinese" class="org.spring.service.impl.Chinese">
	<property name="axe" ref="steelAxe"/>
</bean>
<!--构造注入-->
<bean id="chinese" class="org.spring.service.impl.Chinese">
	<constructor-arg ref="stoneAxe"/>
</bean>

建议采用以设值注入为主,构造注入为辅的注入策略。对于依赖关系无需变化的注入,尽量采用构造注入;而其他的依赖关系的注入,则考虑使用设值注入。

Spring的两个核心接口Spring容器最基本的接口是BeanFactory。它有一个子接口:ApplicationContext。

ApplicationContext有两个常用的实现类:

FileSystemXmlApplicationContext:以基于文件系统的XML配置文件创建实例
ClassPathXmlApplicationContext:以类加载路径下的XML配置文件创建实例
原文地址:https://www.cnblogs.com/weilunhui/p/4143668.html